#!/usr/bin/env python
"""
Footprint PCB layouting program
Copyright (C) 2012 Danny Milosavljevic
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.  If not, see <http://www.gnu.org/licenses/>.
"""

from primitives import MList

from ll import Object

class Toolbox(object):
	def __init__(self, items, tool):
		self.items = items
		self._tool = tool
		self.toolMonitors = MList()
		self.toolMonitors.monitors.cons(self.handleColdplug)
	def handleColdplug(self, action, callback, *args, **kwargs):
		value = self.tool
		callback("change", "tool", value)
	@property
	def tool(self):
		return self._tool
	@tool.setter
	def tool(self, value):
		#print("setting tool", value)
		if self._tool is not value:
			if self._tool is not None:
				self._tool.deselect()
			self._tool = value
			self.notifyToolMonitors("change", "tool", value)
		if self._tool is not None:
			self._tool.select()
	def notifyToolMonitors(self, action, name, value):
		for callback in self.toolMonitors:
			callback(action, name, value)
	def handleEvent(self, canvas, operation, *operands):
		if self.tool and self.tool.handleEvent(canvas, operation, *operands):
			return True
		# local stuff: try to select another tool.
		if operation == "keyPress":
			for item in self.items:
				if item.handleEvent(canvas, operation, *operands):
					self.tool = item
					return True
		return False

class Item(Object):
	def __init__(self, name, keyboardShortcut = None):
		Object.__init__(self)
		self.name = intern(name)
		self.keyboardShortcut = keyboardShortcut
	def select(self): # note: this can also be called when the tool is already selected
		pass
	def deselect(self): # don't rely on that
		pass
	@classmethod
	def getCreationParameters(klass):
		yield ("name", None, "Name")
	def handleEvent(self, canvas, operator, *operands):
		if operator == "keyPress":
			if self.keyboardShortcut and operands[0] == self.keyboardShortcut:
				return True
		return False

