"""Subclass of HubSimulFrame, which is generated by wxFormBuilder."""

import wx
import copy
import os
from fanbotconfig import FanbotConfig




from fanbotframe import  PanelDrawIcon

from bitmap import Bitmap

# Implementing HubSimulFrame
class DesignControl(PanelDrawIcon ):
    def __init__( self, parent):
        PanelDrawIcon.__init__( self, parent )
        print 'DesignControl constructor  '

        self.brush = '1'
        self.drawMode = 0  
        self.brushColor = 0xFFFF;
        self.scaleX = 1
        self.scaleY = 1
        self.bitmap = Bitmap(FanbotConfig.width,FanbotConfig.height)
        self.pointCurrent = wx.Point(0,0)
        self.pointStartDrag = None
        self.pointEndDrag = None
        self.mousePoint = (0,0)
        self.panelIconCanvasOnSize(None)
        self.timer = wx.Timer(self)
        self.Bind(wx.EVT_TIMER, self.timerAnimate, self.timer)
        self.animateIdx = 0
        self.initFileList()

 
                    
    def panelIconCanvasOnPaint( self, event ):
        dc = wx.PaintDC(self.panelIconCanvas)
        dc.BeginDrawing()
        dc.SetUserScale(self.scaleX, self.scaleY)
        dc.Clear()
        dc.DrawBitmap(self.bitmap.getBitmap(),0,0)
        dc.EndDrawing()
        
     
    def panelIconCanvasOnMouseEvents( self, event ):
        
        point = None
        canvas = self.panelIconCanvas
        if event:
            # set mouse cursor
            canvas.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))
            # get device context of canvas
            dc= wx.ClientDC(canvas)
            dc.SetUserScale(self.scaleX, self.scaleY)

            point = event.GetLogicalPosition(dc)
            if point.x < 0 or point.x >= FanbotConfig.width or point.y < 0 or point.y >= FanbotConfig.height:
            	#print 'x,y out of bounds: ',point.x ,':',point.y    
                return
            self.pointCurrent = point    
            #print "mouse event X : " ,point.x , " Y: ",point.y

        if event.LeftDown():
           #print "mouse down X : " ,point.x , " Y: ",point.y
           # Left mouse button down, change cursor to
           # something else to denote event capture
           self.pointStartDrag = point
           cur = wx.StockCursor(wx.CURSOR_CROSS)  
           canvas.SetCursor(cur)
           self.setPixel(point.x, point.y,self.brushColor)        
           # invalidate current canvas
           self.Refresh()

            
        if event.LeftIsDown():
            self.pointDragTo = point
            #print "Dragging to X : " ,point.x , " Y: ",point.y
            cur = wx.StockCursor(wx.CURSOR_CROSS)  
            canvas.SetCursor(cur)
            if self.drawMode == 0:
                self.setPixel(point.x, point.y,self.brushColor)
            if self.drawMode == 1:
                for x in range (self.pointStartDrag.x,point.x):
                    for y in range (self.pointStartDrag.y,point.y):
                        self.setPixel(x, y,self.brushColor)
                                    
            self.panelIconCanvas.Refresh()
                 
    """ Panel drawDesign   """
    def buttonPrevOnButtonClick( self, event ):
        self.prevFrame()
        self.labelFrame.SetLabel(self.getFrameCountAsString())
    
    def buttonNextOnButtonClick( self, event ):
        self.nextFrame()
        self.labelFrame.SetLabel(self.getFrameCountAsString())
  
    def buttonAddFrameOnButtonClick( self, event ):
        self.addFrame()
        self.labelFrame.SetLabel(self.getFrameCountAsString())
        

    def buttonDeleteFrameOnButtonClick( self, event ):
        frnr = self.delFrame()
        self.labelFrame.SetLabel(self.getFrameCountAsString())

    def buttonAddOnButtonClick( self, event ):
        wx.MessageBoxCaptionStr
        dlg = wx.TextEntryDialog(
                self, 'Filename: ',
                'Enter filename', 'Python')

        dlg.SetValue("test.gif")

        if dlg.ShowModal() == wx.ID_OK:
            fn = dlg.GetValue()
            if not fn.find('.gif'):
                fn = fn + '.gif'
            full = 'data/' + fn 
            self.setFilename(full) 
            f = open(full,'w')
            f.close()
            self.saveCurrentFile()   
      
        dlg.Destroy()
        self.listIcons.Append(fn)
         
    def buttonDeleteOnButtonClick( self, event ):
        print 'buttonDeleteOnButtonClick'
        idx = self.listIcons.GetSelection()
        if idx ==  wx.NOT_FOUND:
            return;
        fn = self.listIcons.GetString(idx)
        result = wx.MessageBox('File '+ fn +  ' wissen?', 'File wissen', 
                               wx.OK | wx.CANCEL | wx.ICON_QUESTION)
        if result == wx.OK:
            os.remove('data/' + fn)
            self.listIcons.Delete(idx)
                
    
    def buttonSaveOnButtonClick( self, event ):
        self.saveCurrentFile()
    
    def listIconsOnListBox( self, event ):
        fname = event.GetString()
        print 'selected: ', fname
        self.loadFromFile("data/" + fname)
        self.labelFrame.SetLabel(self.getFrameCountAsString())
      
    
    def sliderAnimateOnScroll( self, event ):
        pos = event.GetPosition()
        self.animate(pos)
        if pos == 0:
            self.labelFrame.SetLabel(self.getFrameCountAsString())

        
        
        
        event.Skip()    
    def initFileList(self):
        for fname in os.listdir("data"):
            if ".gif" in fname:
                #print fname
                self.listIcons.Append(fname)


    def toolBrush1OnToolClicked( self, event ):
        self.brush = '1'
    
    def toolBrush4OnToolClicked( self, event ):
        self.brush = '4'
    
    def toolBrush9OnToolClicked( self, event ):
        self.brush = '9'

    
    def toolDrawLineOnToolClicked( self, event ):
        self.drawMode = 1

    def toolDrawDotOnToolClicked( self, event ):
        self.drawMode = 0
    

    def toolColorOnToolClicked( self, event ):

        dlg = wx.ColourDialog(self)
        dlg.GetColourData().SetChooseFull(True)
        if dlg.ShowModal() == wx.ID_OK:

            # If the user selected OK, then the dialog's wx.ColourData will
            # contain valid information. Fetch the data ...
            data = dlg.GetColourData()

            # ... then do something with it. The actual colour data will be
            # returned as a three-tuple (r, g, b) in this particular case.
            print 'You selected: %s\n' % str(data.GetColour().Get() )
            r,g,b = data.GetColour().Get()
            self.brushColor =   b * 0x10000 + g * 0x100 + r
        dlg.Destroy()
    
    def toolColorBlackOnToolClicked( self, event ):
        print 'colorGray'
        self.brushColor =    0x101010
    
    def toolColorWhiteOnToolClicked( self, event ):
        print 'clororWhite'
        self.brushColor =    0xC0C0C0
    
    def panelIconCanvasOnSize( self, event ):
        rect = self.panelIconCanvas.GetRect()

        self.scaleX = rect.GetWidth() / self.bitmap.width
        self.scaleY = rect.GetHeight() / self.bitmap.height
        #print 'Scale x:y',self.scaleX,':',self.scaleY
        
        self.Refresh()
        
    def loadFromFile(self,fname):
        if self.bitmap.changed:
            result = wx.MessageBox('Bitmap is aangepast. Opslaan?', 'Opslaan', 
                                   wx.OK | wx.CANCEL |wx.ICON_INFORMATION)
            if result == wx.OK:
                self.saveCurrentFile()
        self.bitmap.loadFromFile(fname)
        self.Refresh()

    def saveCurrentFile(self):
        self.bitmap.saveCurrentFile()
  
    def getFilename(self):
        return self.bitmap.filename 
    def setFilename(self,fn):
        self.bitmap.filename = fn 

    def delFrame(self):
        """delete frame at current index.  Do nothing if only one frame        """
        self.bitmap.delFrame()
        self.Refresh()

    def addFrame(self):
        """add frame after the current index.  
        """
        self.bitmap.addFrame()
        self.Refresh()

        
    def prevFrame(self):
        """Go back  to previous  frame in animated GIF. 
        """
        self.bitmap.prevFrame()
        self.Refresh()
 
    def animate(self,speed):
        if speed == 0:
            self.timer.Stop()
        else :
            self.timer.Start(1000 -speed * 100)
 
    def timerAnimate(self,event):
        self.animateIdx += 1
        if self.animateIdx >= self.bitmap.getFrameCount():
            self.animateIdx = 0
        self.bitmap.setFrameNr(self.animateIdx)  
        self.Refresh()  

            
    def getFrameCountAsString(self):
        return '%d/%d' % (self.bitmap.getFrameNr(),self.bitmap.getFrameCount() )    
        
    def nextFrame(self):
        """Advance to next frame in animated GIF. If beyond the last do nothing
        """
        self.bitmap.nextFrame()
        self.Refresh()
        
    def setPixel(self,x,y,colour):
        if self.brush =='1':
            self.bitmap.setPixel(x, y,colour)
        elif self.brush =='4':
            self.bitmap.setPixel(x, y,colour)
            self.bitmap.setPixel(x, y+1,colour)
            self.bitmap.setPixel(x+1, y,colour)
            self.bitmap.setPixel(x+1, y+1,colour)
    
        elif self.brush == '9' and x > 0 and y > 0:
            self.bitmap.setPixel(x, y,colour)
            self.bitmap.setPixel(x, y-1,colour)
            self.bitmap.setPixel(x, y+1,colour)
            self.bitmap.setPixel(x-1, y,colour)
            self.bitmap.setPixel(x-1, y-1,colour)
            self.bitmap.setPixel(x-1, y+1,colour)
            self.bitmap.setPixel(x+1, y,colour)
            self.bitmap.setPixel(x+1, y-1,colour)
            self.bitmap.setPixel(x+1, y+1,colour)

