from picshell.engine.util.Format import Format
from picshell.util.FileUtil import FileUtil
from picshell.ui.Context import Context
import  wx.lib.newevent
import wx
MY_EVT = None
(UpdateEvent, MY_EVT) = wx.lib.newevent.NewEvent()
class CLED:
   # bit in 1,2,4,8,16,32,64,128
   #
   def __init__(self,ui,on,off,address,bit,name="",color="red",varAdrMapping=None):

        self.varname = address
        self.address = Format.toNumber(str(address),varAdrMapping)
        self.bit = bit
        # print "Create LED at address " + str( address ) + "=> %02X" % self.address + " bit %d" % bit
        self.color = color
        self.oldValue = -1
        self.name = name
        self.off = on
        self.on = off
        self.ui = ui
        self.reset()      
        self.type = "CLED"
        Context.frame.Bind(MY_EVT, Context.frame.OnUpdateUI)
        
   def reset(self):
        self.cpt = 0
        
   def execute(self,value): 
       # print "CLED Execute value %02X" % value + " MY ADDRESS %04X" % self.address
       value = value & self.bit

       if value != self.oldValue:
           self.oldValue = value
           evtCallBack = UpdateEvent(value = value, obj = self)
           wx.PostEvent( Context.frame, evtCallBack )

   def UpdateUI(self,value): 
        if value > 0 :
            self.ui.SetBitmap(self.on)
        else :
            self.ui.SetBitmap(self.off)

   def CreateUI(self,parent, psizer ):

        iconPath = Context.icon_path()
        
        self.off =  wx.Image(FileUtil.opj( iconPath + '/gray.GIF'), wx.BITMAP_TYPE_GIF).ConvertToBitmap()

        col = self.color

        if col == "red" :
            self.on =  wx.Image(FileUtil.opj( iconPath + '/red.GIF'), wx.BITMAP_TYPE_GIF).ConvertToBitmap()
        elif col == "blue" :
            self.on =  wx.Image(FileUtil.opj( iconPath + '/blue.GIF'), wx.BITMAP_TYPE_GIF).ConvertToBitmap()
        elif col == "green" :
            self.on =  wx.Image(FileUtil.opj( iconPath + '/green.GIF'), wx.BITMAP_TYPE_GIF).ConvertToBitmap()
        elif col == "orange" :
            self.on =  wx.Image(FileUtil.opj( iconPath + '/orange.GIF'), wx.BITMAP_TYPE_GIF).ConvertToBitmap()
        elif col == "yellow" :
            self.img_on =  wx.Image(FileUtil.opj( iconPath + '/yellow.GIF'), wx.BITMAP_TYPE_GIF).ConvertToBitmap()


        panel = wx.Panel(parent,-1)
        sizer = wx.BoxSizer(wx.HORIZONTAL)
        panel.SetSizer(sizer)
        label = wx.StaticText(panel,-1," " + self.name)
        self.ui = wx.StaticBitmap(panel, -1, self.off, (10, 0), (self.off.GetWidth(), self.off.GetHeight()))
        sizer.Add(self.ui,0,0)
        sizer.Add(label,0,0)
        psizer.Add(panel,0,0)
