### /gui/colorPanel.py

import wx

from gui.imageimport import *

myEVT_CHANGE_COLOR = wx.NewEventType()
EVT_CHANGE_COLOR = wx.PyEventBinder(myEVT_CHANGE_COLOR, 1)

""" 
### cubic method
def dis(Color, ColorDis, p):
	for i in range(3):
		c1 = Color[i]
		c2 = ColorDis[i]
		if not (c2 - 255 * p <= c1 <= c2 + 255 * p):
			return False
	return True
"""

### new spherical method - in RGB
def dis(color, colorDis, p):
	r = 0
	for i in range(3):
		r += (color[i] - colorDis[i]) ** 2
	if r <= ((256 * p) ** 2):
		return True
	return False

### return ratio
def rdis(color, colorDis, p):
	if p == 0: return -1
	r = 0
	for i in range(3):
		r += (color[i] - colorDis[i]) ** 2
	if r <= ((256 * p) ** 2):
		r = 1 - r / float((256 * p) ** 2)
		return r
	return -1

	
### new spherical method in two colors
### return ratio
def rdis2(C1, C2, Cd):
	### prepared functions for dis2
	def distance(point1, point2):
		r = 0
		for i in range(3):
			r += (point1[i] - point2[i]) ** 2
		return r
	def product(vector1, vector2):
		r = 0
		for i in range(3):
			r += vector1[i] * vector2[i]
		return r
	def vector(point1, point2):
		return (point2[0] - point1[0], point2[1] - point1[1], point2[2] - point1[2])

	a = 0
	for i in range(3):
		if C1[i] == C2[i]: a += 1
	if a == 3: return -1
		
	# get the middle point
	M = ( \
		 (C1[0] + C2[0]) / 2.0, \
		 (C1[1] + C2[1]) / 2.0, \
		 (C1[2] + C2[2]) / 2.0 \
		)
	# get the sphere's radius
	r  = distance(C1, M)
	# get M-Cd distance
	rd = distance(M, Cd)
	if r < rd: return -1
	
	# get the projection coordinate H
	vC1C2 = vector(C1, C2)
	vC1Cd = vector(C1, Cd)
	k = product(vC1Cd, vC1C2) / float(product(vC1C2, vC1C2))
	# return pitch
	return k
	
	
class MyEvent(wx.PyCommandEvent):
	def __init__(self, evtType, id):
		wx.PyCommandEvent.__init__(self, evtType, id)
		self.color = None
	def SetColor(self, color):
		self.color = color
	def GetColor(self):
		return self.color

class ColorPanel(wx.Panel):
	def __init__(self,parent):
		wx.Panel.__init__(self,parent,-1,size=wx.DefaultSize,style=wx.SIMPLE_BORDER)
		
		# self.Canvas = parent.Canvas
		self.Bind(wx.EVT_LEFT_DOWN,self.OnClick)
		self.Bind(wx.EVT_RIGHT_DOWN,self.OnClick)
		self.SetSize((26,26))
		self.color = None
		self.SetBackgroundColour('black')
	def SetColor(self,color):
		self.SetBackgroundColour(color)
		self.Refresh()
	def OnClick(self,uselessEvent):
		dlg = wx.ColourDialog(self, self.color)
		dlg.GetColourData().SetChooseFull(True)
		
		if dlg.ShowModal() == wx.ID_OK:
			color = dlg.GetColourData().GetColour().Get()
			self.SetColor(color)
			
			# make event
			evt = MyEvent(myEVT_CHANGE_COLOR, self.GetId())
			evt.SetColor(color)
			self.color = dlg.GetColourData()
			
			self.GetEventHandler().ProcessEvent(evt)
			uselessEvent.Skip()