#! /usr/bin/env python
#  -*- coding: utf-8 -*-
#
# GUI module generated by PAGE version 4.24.1
#  in conjunction with Tcl version 8.6
#    Aug 01, 2019 02:22:22 PM CEST  platform: Windows NT

import sys
import tkinter

from ICO3Plugin.Plugin.ICO3FramePlugin import ICO3FramePlugin
from ICO3Utilities.Debug.LogDebug import ICO3Log

try:
    import Tkinter as tk
except ImportError:
    import tkinter as tk

try:
    import ttk
    py3 = False
except ImportError:
    import tkinter.ttk as ttk
    py3 = True

class MessageFramePlugin(ICO3FramePlugin):


    theFrame = None
    theMainframe = None

    # thePluginFrame = None
    theSenderHeader = None
    theReceiver = None

    def on_closing(self):
        # ICO3Log.print("Plugin","Close Application")
        # self.removeMe()
        # sys.exit(0)
        pass

    def __init__(self, xMainFrame = None, XY = None) :         #, top=None):
#        tk.Toplevel.__init__(self)
        '''This class configures and populates the toplevel window.
           top is the toplevel containing window.'''
        if xMainFrame is not None:
            self.theMainframe = xMainFrame
        if self.theMainframe is None:
            return

        XYPos = "154,120"
        if XY != None:
            XYPos  = XY
            pass
        xGeometry = "600x450" + self.getXYExtention(XYPos)
        ICO3Log.print("Plugin","Geometrie MessageFrame : " + xGeometry)
        _bgcolor = '#d9d9d9'  # X11 color: 'gray85'
        _fgcolor = '#000000'  # X11 color: 'black'
        _compcolor = '#d9d9d9' # X11 color: 'gray85'
        _ana1color = '#d9d9d9' # X11 color: 'gray85'
        _ana2color = '#ececec' # Closest X11 color: 'gray92'
        self.style = ttk.Style()
        if sys.platform == "win32":
            self.style.theme_use('winnative')
        self.style.configure('.',background=_bgcolor)
        self.style.configure('.',foreground=_fgcolor)
        self.style.map('.',background=
            [('selected', _compcolor), ('active',_ana2color)])
        self.theFrame = tk.Toplevel(self.theMainframe)
        self.theFrame.geometry(xGeometry)         #top
        self.theFrame.title("Icocube Test")
        self.theFrame.configure(background="#d9d9d9")
        self.theFrame.configure(highlightbackground="#d9d9d9")
        self.theFrame.configure(highlightcolor="black")

        self.theFrame.protocol("WM_DELETE_WINDOW", self.on_closing)

        self.Label1 = tk.Label(self.theFrame)
        self.Label1.place(relx=0.067, rely=0.0, height=26, width=64)
        self.Label1.configure(activebackground="#f9f9f9")
        self.Label1.configure(activeforeground="black")
        self.Label1.configure(background="#d9d9d9")
        self.Label1.configure(disabledforeground="#a3a3a3")
        self.Label1.configure(foreground="#000000")
        self.Label1.configure(highlightbackground="#d9d9d9")
        self.Label1.configure(highlightcolor="black")
        self.Label1.configure(text='''Message''')

        self.BTSendMessge = tk.Button(self.theFrame)
        self.BTSendMessge.place(relx=0.75, rely=0.244, height=33, width=107)
        self.BTSendMessge.configure(activebackground="#ececec")
        self.BTSendMessge.configure(activeforeground="#000000")
        self.BTSendMessge.configure(background="#d9d9d9")
        self.BTSendMessge.configure(command=self.SendtheMessage)
        self.BTSendMessge.configure(disabledforeground="#a3a3a3")
        self.BTSendMessge.configure(foreground="#000000")
        self.BTSendMessge.configure(highlightbackground="#d9d9d9")
        self.BTSendMessge.configure(highlightcolor="black")
        self.BTSendMessge.configure(pady="0")
        self.BTSendMessge.configure(text='''Send Message''')

        self.Label2 = tk.Label(self.theFrame)
        self.Label2.place(relx=0.2, rely=0.289, height=26, width=167)
        self.Label2.configure(background="#d9d9d9")
        self.Label2.configure(disabledforeground="#a3a3a3")
        self.Label2.configure(foreground="#000000")
        self.Label2.configure(text='''Messages processed List''')

        self.STextMessage = ScrolledText(self.theFrame)
        self.STextMessage.place(relx=0.2, rely=0.022, relheight=0.209
                , relwidth=0.742)
        self.STextMessage.configure(background="white")
        self.STextMessage.configure(font="TkTextFont")
        self.STextMessage.configure(foreground="black")
        self.STextMessage.configure(highlightbackground="#d9d9d9")
        self.STextMessage.configure(highlightcolor="black")
        self.STextMessage.configure(insertbackground="black")
        self.STextMessage.configure(insertborderwidth="3")
        self.STextMessage.configure(selectbackground="#c4c4c4")
        self.STextMessage.configure(selectforeground="black")
        self.STextMessage.configure(width=10)
        self.STextMessage.configure(wrap="none")

        self.STextMessageList = ScrolledText(self.theFrame)
        self.STextMessageList.place(relx=0.2, rely=0.356, relheight=0.609
                , relwidth=0.742)
        self.STextMessageList.configure(background="white")
        self.STextMessageList.configure(font="TkTextFont")
        self.STextMessageList.configure(foreground="black")
        self.STextMessageList.configure(highlightbackground="#d9d9d9")
        self.STextMessageList.configure(highlightcolor="black")
        self.STextMessageList.configure(insertbackground="black")
        self.STextMessageList.configure(insertborderwidth="3")
        self.STextMessageList.configure(selectbackground="#c4c4c4")
        self.STextMessageList.configure(selectforeground="black")
        self.STextMessageList.configure(width=10)
        self.STextMessageList.configure(wrap="none")
        self.STextMessageList.configure(state="disable")

        self.BTClearList = tk.Button(self.theFrame)
        self.BTClearList.place(relx=0.05, rely=0.6, height=33, width=72)
        self.BTClearList.configure(activebackground="#ececec")
        self.BTClearList.configure(activeforeground="#000000")
        self.BTClearList.configure(command=self.CallBackClearList)
        self.BTClearList.configure(background="#d9d9d9")
        self.BTClearList.configure(disabledforeground="#a3a3a3")
        self.BTClearList.configure(foreground="#000000")
        self.BTClearList.configure(highlightbackground="#d9d9d9")
        self.BTClearList.configure(highlightcolor="black")
        self.BTClearList.configure(pady="0")
        self.BTClearList.configure(text='''Clear List''')

    def SendtheMessage(self):
        TextInput = self.STextMessage.get("1.0", tkinter.END)
        ICO3Log.print("Plugin","we send : " + TextInput)
        self.DisplayMessage("<<<"+ TextInput)


        self.sendTextMessage(TextInput)
        self.clearInputText()

        ICO3Log.print("Plugin","Send Message Clicked")

    def DisplayMessage(self, xMsg):
        self.STextMessageList.configure(state="normal")
        self.STextMessageList.insert('1.0', xMsg)
        self.STextMessageList.configure(state="disable")

    def clearInputText(self):
        self.STextMessage.delete('1.0', tkinter.END)

    def CallBackClearList(self):
        self.STextMessageList.configure(state="normal")
        self.STextMessageList.delete('1.0', tkinter.END)
        self.STextMessageList.configure(state="disable")
        ICO3Log.print("Plugin","MessageList Clear Clicked")

    def sendTextMessage(self, xTxt):
        return self.sendMessageToTarget("TargetTest", xTxt)

        # xxMsg = ICO3Message.ICO3Message.createMessage(self.theSenderHeader, xTxt)
        # return self.theModuleMaster.sendMessageCheck(xxMsg)

    ExtraReceiveLF = False
    def reveiveMessage(self, xMsg):
        ICO3Log.print("Plugin","Message -->>" + str(xMsg))
        xtrLF = ""
        if self.ExtraReceiveLF == True:
            xtrLF = "\n"
        self.DisplayMessage(">>>"+ str(xMsg)+xtrLF)
        return 1

    def callBackReceiveMessage(self, xMessage):
        return self.reveiveMessage(xMessage.getPayloadString())




    def initPlugin(self, Argvs):
        # xTargetTest = self.getTaskParameterFlat("TargetTest")
        # if xTargetTest is not None:
        #     self.theReceiver = xTargetTest.Port
        #     if xTargetTest.Target is not None:
        #         XLP = self.nodeWayProcessing(xTargetTest.Target)
        #         self.theSenderHeader = ICO3MessageHeader.ICO3MessageHeader.parseFromString(XLP)

        self.theFrame.title(Argvs + " (" + str(self.theModuleMaster.ModuleID) + ")")
        xLF = self.getExtraParameterValue("ReceiveLF")
        if xLF == "True":
            self.ExtraReceiveLF = True
        pass

    def startPlugin(self):
        self.theTaskEvent = self.createInstallTaskEventFromTask("TargetTest", self.callBackReceiveMessage)
        # if self.theReceiver is not None:
        #     try:
        #         xTsk = int(self.theReceiver)
        #         xEvent = ICO3MessageEvent()
        #         xEvent.CallBack = self.callBackReceiveMessage
        #         xEvent.TasKID = xTsk
        #         self.theModuleMaster.installTaskEvent(xEvent)
        #     except:
        #         pass
        # pass

    def stopPlugin(self):
        self.removeTaskEvent(self.theTaskEvent)
        self.theFrame.destroy()
        pass

    def MainLoopProcess(self):
        pass


# The following code is added to facilitate the Scrolled widgets you specified.
class AutoScroll(object):
    '''Configure the scrollbars for a widget.'''

    def __init__(self, master):
        #  Rozen. Added the try-except clauses so that this class
        #  could be used for scrolled entry widget for which vertical
        #  scrolling is not supported. 5/7/14.
        try:
            vsb = ttk.Scrollbar(master, orient='vertical', command=self.yview)
        except:
            pass
        hsb = ttk.Scrollbar(master, orient='horizontal', command=self.xview)

        #self.configure(yscrollcommand=_autoscroll(vsb),
        #    xscrollcommand=_autoscroll(hsb))
        try:
            self.configure(yscrollcommand=self._autoscroll(vsb))
        except:
            pass
        self.configure(xscrollcommand=self._autoscroll(hsb))

        self.grid(column=0, row=0, sticky='nsew')
        try:
            vsb.grid(column=1, row=0, sticky='ns')
        except:
            pass
        hsb.grid(column=0, row=1, sticky='ew')

        master.grid_columnconfigure(0, weight=1)
        master.grid_rowconfigure(0, weight=1)

        # Copy geometry methods of master  (taken from ScrolledText.py)
        if py3:
            methods = tk.Pack.__dict__.keys() | tk.Grid.__dict__.keys() \
                  | tk.Place.__dict__.keys()
        else:
            methods = tk.Pack.__dict__.keys() + tk.Grid.__dict__.keys() \
                  + tk.Place.__dict__.keys()

        for meth in methods:
            if meth[0] != '_' and meth not in ('config', 'configure'):
                setattr(self, meth, getattr(master, meth))

    @staticmethod
    def _autoscroll(sbar):
        '''Hide and show scrollbar as needed.'''
        def wrapped(first, last):
            first, last = float(first), float(last)
            if first <= 0 and last >= 1:
                sbar.grid_remove()
            else:
                sbar.grid()
            sbar.set(first, last)
        return wrapped

    def __str__(self):
        return str(self.master)

def _create_container(func):
    '''Creates a ttk Frame with a given master, and use this new frame to
    place the scrollbars and the widget.'''
    def wrapped(cls, master, **kw):
        container = ttk.Frame(master)
        container.bind('<Enter>', lambda e: _bound_to_mousewheel(e, container))
        container.bind('<Leave>', lambda e: _unbound_to_mousewheel(e, container))
        return func(cls, container, **kw)
    return wrapped

class ScrolledText(AutoScroll, tk.Text):
    '''A standard Tkinter Text widget with scrollbars that will
    automatically show/hide as needed.'''
    @_create_container
    def __init__(self, master, **kw):
        tk.Text.__init__(self, master, **kw)
        AutoScroll.__init__(self, master)

import platform
def _bound_to_mousewheel(event, widget):
    child = widget.winfo_children()[0]
    if platform.system() == 'Windows' or platform.system() == 'Darwin':
        child.bind_all('<MouseWheel>', lambda e: _on_mousewheel(e, child))
        child.bind_all('<Shift-MouseWheel>', lambda e: _on_shiftmouse(e, child))
    else:
        child.bind_all('<Button-4>', lambda e: _on_mousewheel(e, child))
        child.bind_all('<Button-5>', lambda e: _on_mousewheel(e, child))
        child.bind_all('<Shift-Button-4>', lambda e: _on_shiftmouse(e, child))
        child.bind_all('<Shift-Button-5>', lambda e: _on_shiftmouse(e, child))

def _unbound_to_mousewheel(event, widget):
    if platform.system() == 'Windows' or platform.system() == 'Darwin':
        widget.unbind_all('<MouseWheel>')
        widget.unbind_all('<Shift-MouseWheel>')
    else:
        widget.unbind_all('<Button-4>')
        widget.unbind_all('<Button-5>')
        widget.unbind_all('<Shift-Button-4>')
        widget.unbind_all('<Shift-Button-5>')

def _on_mousewheel(event, widget):
    if platform.system() == 'Windows':
        widget.yview_scroll(-1*int(event.delta/120),'units')
    elif platform.system() == 'Darwin':
        widget.yview_scroll(-1*int(event.delta),'units')
    else:
        if event.num == 4:
            widget.yview_scroll(-1, 'units')
        elif event.num == 5:
            widget.yview_scroll(1, 'units')

def _on_shiftmouse(event, widget):
    if platform.system() == 'Windows':
        widget.xview_scroll(-1*int(event.delta/120), 'units')
    elif platform.system() == 'Darwin':
        widget.xview_scroll(-1*int(event.delta), 'units')
    else:
        if event.num == 4:
            widget.xview_scroll(-1, 'units')
        elif event.num == 5:
            widget.xview_scroll(1, 'units')
