# -*- coding: utf-8 -*-
# ok got crude visual of send panels, need recieve window
# need to move to correct types of widgets
# link back to controller so save refernce
# todo's
#       drop down list for send area
#       scroll bar on recieve
#       auto scrolling for reciefe

# fix colors
# make line single lines
# make easy to have n entry lines



import  Tkinter
from    Tkinter import *
import  sys

class GUI:


    def __init__( self, aController, aParent ):

        self.myParent       = aParent
        self.myController   = aController
        self.myParameters   = aController.myParameters

        self.mySends        = []
        self.mySendsButtons = []
        self.mySendsData    = []

        self.myMaxMyLables  = 6   # number of lables, normally used for parameters
        self.myLables       = []  # lables normally for parameters

        #------ constants for controlling layout ------
        self.button_width         = 6

        self.button_padx          = "2m"
        self.button_pady          = "1m"

        self.buttons_frame_padx   = "3m"
        self.buttons_frame_pady   = "2m"
        self.buttons_frame_ipadx  = "3m"
        self.buttons_frame_ipady  = "1m"

        self.next_frame = 0    # position row for frames

        self.root      = Tkinter.Frame( aParent )

        #self.root.grid( column=1, row=1 )  # this seems to set up the col grid in the root
        #self.root.pack( expand = True, sticky = E+W )  # this also works, why needed? sticky not an option here

        # this frame self.root may be rudundant with its parent
        self.root.grid(  column=0,row=0, sticky= E+W+N+S )


        self.makeParmFrame( self.root, "white" )

        self.myParent.grid_columnconfigure( 0, weight=1 ) # final missing bit of magic
        self.myParent.grid_rowconfigure(    0, weight=1 )


        self.send_frames  = []
        for ix in range( self.myParameters.gui_sends ):
            self.send_frames.append( self.makeSendFrame( self.root, "gray"    ) )

        self.showParms()
#
# #        self.send_frames.append( self.makeSendFrame( self.root, "gray"    ) )
# #        self.send_frames.append( self.makeSendFrame( self.root, "red"     ) )
# #        self.send_frames.append( self.makeSendFrame( self.root, "blue"    ) )
# #        self.send_frames.append( self.makeSendFrame( self.root, "yellow"  ) )
#
#
        self.rec_frame    = self.makeRecFrame( self.root, "green" )

        self.root.grid_columnconfigure( 0, weight=1 )
        self.root.grid_rowconfigure(    0, weight=0 )

        print "self.next_frame configure", self.next_frame
        self.root.grid_rowconfigure( ( self.next_frame - 1 ), weight=1 )
        #self.root.grid_rowconfigure( ( 5, 1 )

#         #self.myParent.grid_columnconfigure(0,weight=1)
#==============================================================================


    def setOpen( self, status ):

        self.myLables[ 0 ].config( text    = "Port: " + status  )

#        if boolval:
#            self.myLables[ 0 ].config( text    = "port: Open"  )
#        else:
#            self.myLables[ 0 ].config( text    = "port: Open Fail"  )

        return


    def showParms( self,  ) :  # show befor open, yes, but frist 2 parms are ini file and port status
        """
        get parms from Parameters and display
        """

        spacer   = "                                     "
        lab_len  = 20

        self.myLables[ 0 ].config( text    = ("Port: Closed"                                        + spacer )[0:lab_len]   )

        self.myLables[ 1 ].config( text    = ("Type: "       + self.myParameters.getCommTypeAsStr() + spacer )[0:lab_len]   )

        self.myLables[ 2 ].config( text    = ("PortID: "     + self.myParameters.getPortAsStr()     + spacer )[0:lab_len]   )
        self.myLables[ 3 ].config( text    = ("Baud: "       + self.myParameters.getBaudrateAsStr() + spacer )[0:lab_len]   )

        self.myLables[ 4 ].config( text    = ("StopBits: "   + self.myParameters.getStopbitsAsStr() + spacer )[0:lab_len]   )
        self.myLables[ 5 ].config( text    = ("Parity: "     + self.myParameters.getParityAsStr()   + spacer )[0:lab_len]   )

        return


    def printToSendArea( self, data ):

        sdata = ">>>" + data  + "\n"
        self.showRecFrame( sdata )   # or just use directly
        return


    def doSendButton( self, event ) :  # how do we identify the button
        """
        any send button
        for at least now do the send echo locally ( and crlf or always use locally )
        """

        #identify the control, one of mySendsButtons
        control_ix = -1
        for index, item in enumerate( self.mySendsButtons ):

            if item == event.widget:
                control_ix = index
                break

        # now we get text out of the ajoining control

        # this is for a text not an entry
        #contents = self.mySendsData[control_ix].get(1.0, END)

        # for an entry
        contents = self.mySendsData[control_ix].get()

        #self.myController.log( contents, "print" )
        if self.myController.myParameters.echoSend:
            self.printToSendArea( contents )

        self.myController.send( contents )
        return

    def showRecFrame( self, adata ):
            self.myRecText.insert( END, adata, )
            self.myRecText.see( END )
            return


    def makeSendFrame( self, parent, color ):  # if this were a class then could access its variables later
            """
            make a new send frame and put it in the next place down
            """

            send_frame  = Frame( parent, width=300, height=200, bg="red", relief=RAISED, borderwidth=1 )
            send_frame.grid( row=self.next_frame, column=0, sticky= E + W + N  )
            self.next_frame += 1
            print "self.next_frame ", self.next_frame

            #text0 = Text( send_frame , width=50, height=2 )
            #text0.configure( bg = color )

            text0 = Entry( send_frame , ) # width=50, ) # height=2 )
            text0.configure( bg = color )

            #Entry( iframe, textvariable=v )

            button0 = Button( send_frame , width=10, height=2, text = "Send" )
            button0.bind( "<Button-1>", self.doSendButton ) # function name no () which would call function then

            # position
            button0.pack( side = LEFT )
            text0.pack(   side = LEFT, fill=BOTH, expand=1)  #  fill X Y BOTH but also need expand=1 ( or prehaps True )

            # save for send function
            self.mySends.append( send_frame )
            self.mySendsButtons.append( button0 )
            self.mySendsData.append( text0 )

            # if use grid, but we may be packing
            #send_frame.grid_columnconfigure( 0, weight=0 )
            #send_frame.grid_rowconfigure(    0, weight=0 )

            return send_frame


    def makeSendDDFrame( self, parent, color ):  # if this were a class then could access its variables later
            """
            drop down, not text in testing
            make a new send frame and put it in the next place down
            """

            send_frame  = Frame( parent, width=300, height=200, bg="blue", relief=RAISED, borderwidth=1 )
            send_frame.grid( row=self.next_frame, column=0 )
            self.next_frame += 1

            text0 = Text( send_frame , width=50, height=2 )
            text0.configure( bg = color )

            button0 = Button( send_frame , width=10, height=2, text = "Send" )
            button0.bind( "<Button-1>", self.sendButton ) # function name no () which would call function then

            # position
            button0.pack( side = LEFT )
            text0.pack( side = LEFT )

            # save for send function
            self.mySends.append( send_frame )
            self.mySendsButtons.append( button0 )
            self.mySendsData.append( text0 )

            return send_frame


    # -----  parm frame

    def doOpenButton( self, event):
        self.myController.openDriver()
        return


    def doCloseButton( self, event):

        self.myController.closeDriver()
        return


    def doTest1Button( self, event):

        # next code when used for looping
        self.myController.log( "setting looping true", "print" )
        self.myController.looping = True
        return


    def doTest2Button( self, event):

        self.myController.log( "setting looping false", "print" )
        self.myController.looping = False
        return


    def makeParmFrame( self, parent, color ):  # if this were a class then could access its variables later
            """
            make frame and place it
            open/close port
            show port pams
            test button for recieve simulation
            whole parm frame is managed by a grid inside the grid of the whole window
            """

            iframe  = Tkinter.Frame( parent, width=300, height=200, bg ="gray", relief=RAISED, borderwidth=1 )

            iframe.grid( row=self.next_frame, column=0, sticky = E + W + N + S )   # + N + S  )  # actually only expands horiz

            #iframe.grid( row = self.next_frame, column=0, sticky='EW' )
            self.next_frame += 1
            #print "self.next_frame ", self.next_frame

            buttonOpen = Button( iframe , width=10, height=2, text = "Open" )
            buttonOpen.bind( "<Button-1>", self.doOpenButton )

            buttonClose = Button( iframe , width=10, height=2, text = "Close" )
            buttonClose.bind( "<Button-1>", self.doCloseButton )


            buttonOpen.grid(  row = 0, column=0, sticky='E' )
            buttonClose.grid( row = 1, column=0, sticky='E' )

            buttonTest1 = Button( iframe , width=10, height=2, text = "Loop On" )
            buttonTest1.bind( "<Button-1>", self.doTest1Button ) #

            buttonTest2 = Button( iframe , width=10, height=2, text = "Loop Off" )
            buttonTest2.bind( "<Button-1>", self.doTest2Button )


            buttonTest1.grid(  row = 0, column=1, sticky='E' )
            buttonTest2.grid(  row = 1, column=1, sticky='E' )


            for ix in range( self.myMaxMyLables ):
                    self.myLables.append( Label( iframe, text = "lbls" + str( ix ), relief = RAISED,  )  )
                    self.myLables[ ix ]

            lrow    = 0
            lcol    = 2
            for ilabel in self.myLables:
                 #print "label at ", lrow, lcol
                 #ilabel.grid( row = lrow, column=lcol, sticky=W+E+N+S  )   # relief = RAISED)
                 ilabel.grid( row=lrow, column=lcol, sticky=E + W  )

                 lrow   += 1
                 if lrow >= 2:

                    lrow   =  0
                    lcol   += 1


            for ix in range(  2, lcol  ):
                 iframe.grid_columnconfigure( ix, weight=0 )
                 #iframe.grid_rowconfigure(    0, weight=0 )

            return


    def doClearButton( self, event):
        """
        for the clear button
        clear the recieve area

        """
        self.myRecText.delete( 1.0, END )
        return


    def makeRecFrame( self, parent, color ):


        iframe  = Frame( parent, width=300, height=800, bg ="blue", relief=RAISED, borderwidth=1,  )
        iframe.grid( row = self.next_frame, column=0, sticky= E + W + N + S )
        self.next_frame += 1

        bframe  = Frame( iframe, bg ="black", width=30  ) # width=300, height=800, bg ="blue", relief=RAISED, borderwidth=1,  )
        bframe.grid( row=0, column=0, sticky = N + S )


        text0 = Text( iframe , width=50, height=20 )
        text0.configure( bg = "red" )

        s_text0 = Scrollbar( iframe  )  # LEFT left
        s_text0.grid( row=0, column=2, sticky = N + S )

        s_text0.config( command=text0.yview )
        text0.config( yscrollcommand=s_text0.set )

        text0.grid( row=0, column=1, sticky = N + S + E + W  )

        self.myRecText  = text0   # not very ellegant

        iframe.grid_columnconfigure( 1, weight=1 )
        iframe.grid_rowconfigure(    0, weight=1 )

        # now into the button frame bframe

        # spacer
        s_frame = Frame( bframe, bg ="green", height=20 ) # width=30  )

        s_frame.grid( row=0, column=0  )

        b_clear = Button( bframe , width=10, height=2, text = "Clear" )

        b_clear.bind( "<Button-1>", self.doClearButton )

        b_clear.grid( row=1, column=0   )

        b_copy = Button( bframe , width=10, height=2, text = "Copy" )

        #b_copy.bind( "<Button-1>", self.doClearButton )

        b_copy.grid( row=2, column=0   )


        return



    def makeRecFramexxxxxx( self, parent, color ):  # if this were a class then could access its variables later
            """
            make a new rec frame and place it
            """


            iframe  = Frame( parent, width=300, height=800, bg ="blue", relief=RAISED, borderwidth=1,  )
            iframe.grid( row = self.next_frame, column=0, sticky= E + W + N + S )
            self.next_frame += 1

            text0 = Text( iframe , width=50, height=20 )
            text0.configure( bg = color )

            button0 = Button( iframe , width=10, height=2, text = "Clear" )

            button0.bind( "<Button-1>", self.doClearButton ) # fun
            # position
            button0.pack( side = LEFT )
            text0.pack(   side = LEFT, fill=BOTH, expand=1 )

            # t_start = Text(left, width=20)
            #t_start.pack(side=LEFT, fill=Y)
            s_text0 = Scrollbar( iframe  )  # LEFT left
            s_text0.pack( side=RIGHT, fill=Y )

            s_text0.config( command=text0.yview )
            text0.config( yscrollcommand=s_text0.set )

            self.myRecText  = text0   # not very ellegant

            return



#   ========================= end ============================



