#! /usr/bin/env python
#  -*- coding: utf-8 -*-
#
# GUI module generated by PAGE version 4.24.1
#  in conjunction with Tcl version 8.6
#    Aug 02, 2019 01:17:16 PM CEST  platform: Windows NT
import importlib
import sys
import uuid
from pathlib import Path

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
from tkinter import messagebox, filedialog

# import uuid

from ICO3Core.Node import ICO3LocalNode
from ICO3Utilities.Xml.XmlProcess import XmlProcessing

top = None

def vp_start_gui():
    '''Starting point when module is the main routine.'''
    global val, w, root, topw
    root = tk.Tk()
    topw = ICO3StartIcocube (root)
    #ICO3Starter_support.init(root, top)
    root.protocol("WM_DELETE_WINDOW", on_closing)
    root.mainloop()

w = None
def create_ICO3Starter(root, *args, **kwargs):
    '''Starting point when module is imported by another program.'''
    global baseFrame, w_win, rt, top
    rt = root
    w = tk.Toplevel (root)
    top = ICO3StartIcocube (w)
    #ICO3Starter_support.init(w, top, *args, **kwargs)
    return (w, top)

def destroy_ICO3Starter():
    global w, topw
    topw.destroy()
    topw = None

def on_closing():
    if messagebox.askokcancel("Quit", "Do you want to quit?"):
        destroy_ICO3Starter()

        root.destroy()
        exit(0)

class ICO3StartIcocube:
    theMainFrame = None
    theMainNode = None


    @staticmethod
    def destroy_ICO3Starter():
        global w, topw
        topw.destroy()
        topw = None

    @staticmethod
    def on_closing():
        if messagebox.askokcancel("Quit", "Do you want to quit?"):
            destroy_ICO3Starter()
            root.destroy()
            exit(0)

    @staticmethod
    def launch():
        '''Starting point when module is the main routine.'''
        global  root, topw      #  val, w,
        root = tk.Tk()
        topw = ICO3StartIcocube (root)
        #ICO3Starter_support.init(root, top)
        root.protocol("WM_DELETE_WINDOW", ICO3StartIcocube.on_closing)
        root.mainloop()

    def __init__(self, top=None):
        '''This class configures and populates the toplevel window.
           top is the toplevel containing window.'''
        _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.theMainFrame = top
        top.geometry("300x150+300+100")
        Argv = sys.argv
        if (len(Argv) > 2):
            top.title(Argv[1])
        else:
            top.title("Icocube Starter")
        top.configure(background="#d9d9d9")

        self.BTStartIcocube = tk.Button(top)
        self.BTStartIcocube.place(relx=0.080, rely=0.155, height=33, width=250)
        self.BTStartIcocube.configure(activebackground="#ececec")
        self.BTStartIcocube.configure(activeforeground="#000000")
        self.BTStartIcocube.configure(background="#d9d9d9")
        self.BTStartIcocube.configure(command=self.CBStartIcocube)
        self.BTStartIcocube.configure(disabledforeground="#a3a3a3")
        self.BTStartIcocube.configure(foreground="#000000")
        self.BTStartIcocube.configure(highlightbackground="#d9d9d9")
        self.BTStartIcocube.configure(highlightcolor="black")
        self.BTStartIcocube.configure(pady="0")
        self.BTStartIcocube.configure(text='''Start Icocube Server''')
        self.BTStartIcocube.configure(width=250)

        self.BTStopIcocube = tk.Button(top)
        self.BTStopIcocube.place(relx=0.080, rely=0.500, height=33, width=250)
        self.BTStopIcocube.configure(activebackground="#ececec")
        self.BTStopIcocube.configure(activeforeground="#000000")
        self.BTStopIcocube.configure(background="#d9d9d9")
        self.BTStopIcocube.configure(command=self.CBStopIcocube)
        self.BTStopIcocube.configure(disabledforeground="#a3a3a3")
        self.BTStopIcocube.configure(foreground="#000000")
        self.BTStopIcocube.configure(highlightbackground="#d9d9d9")
        self.BTStopIcocube.configure(highlightcolor="black")
        self.BTStopIcocube.configure(pady="0")
        self.BTStopIcocube.configure(text='''Stop Icocube Server''')
        self.BTStopIcocube.configure(width=250)
        self.BTStopIcocube.config(state="disable")
        print(" User Directory : " + str(Path.home()))

    def load_file(self):
        fileName = filedialog.askopenfilename(initialdir='./Icocube', filetypes=(("Xml files", "*.xml") , ("All files", "*.*")))
        return fileName

    def CBStartIcocube(self):
        print("it's ICOCUBE STARTER")
        StarterDir = self.load_file()
        if StarterDir == "":
            return

        # Argv = sys.argv
        # if (len(Argv) > 2):
        #     print(str(Argv))
        # else:
        #     exit()
        # StarterDir = Argv[2]
        # if StarterDir.find("$HOME") != -1:
        #     StarterDir = StarterDir.replace("$HOME", str(Path.home()))
        print(" Parameters File : "+ StarterDir)
        XmlRoot = XmlProcessing.process(StarterDir, "ICO3Node")
        if (XmlRoot == None):
            print("XML ERROR --> Exit()")
            exit()

        self.theMainNode = ICO3LocalNode.ICO3LocalNode.create(XmlRoot)
        self.theMainNode.setMainFrame(self.theMainFrame)
        if (self.theMainNode == None):
            print("Cannot Create Main Node")
            exit()
        self.theMainNode.setupDebug()
        self.theMainNode.installParameters()
        print("Node Installed")

        if not self.theMainNode.checkNode():
            print("Node Corrupted Verifiy It")

        self.theMainNode.initNodeSystem()
        self.theMainNode.startAllNodePluginApp()

        self.theMainNode.startAllNodeConnection()
        self.theMainNode.startRTCLoopProcess()

        #XmlRoot1 = XmlProcessing.process("MongoDBClient.xml", "ICO3Node")
        #theNode1 = ICO3LocalNode.ICO3LocalNode.create(XmlRoot1)

        NPElement = XmlProcessing.getTagElement(XmlRoot, "ICO3NodeParameters")
        NPName = XmlProcessing.getAttributeValue(NPElement, "Name")
        NPNodeID = XmlProcessing.getAttributeValue(NPElement, "NodeID")
        NPNodeMode = XmlProcessing.getAttributeValue(NPElement, "NodeMode")
        NPNodeSN = XmlProcessing.getAttributeValue(NPElement, "NodeSN")
        NodeUUID = None
        if (NPNodeSN != None):
            NodeUUID = uuid.UUID(NPNodeSN)
        print("Create Node Name=" + str(NPName) + "  ID=" + str(
            NPNodeID + "  Mode=" + str(NPNodeMode + "  SN=" + str(NodeUUID))))
        TestUUID = uuid.UUID("35a81b1a-c3ac-4ee9-9803-ccf649b31007")
        if (NodeUUID == TestUUID):
            print("Hourra ->" + str(TestUUID))
        self.BTStartIcocube.config(state="disable")
        self.BTStopIcocube.config(state="normal")
        astr = "ABCDEFGH"
        bastr = bytearray(map(ord, astr))

        XXID = uuid.uuid4()
        xudA = XXID.bytes
        xudB = XXID.bytes_le

        xudAB = XXID.hex
        xudBA = xudA.hex()
        xudBB = xudB.hex()
        xudC = xudA + xudB + bastr

        xudCA = xudC.hex()
        print(str(XXID))
        self.update_MainLoop()

    def update_MainLoop(self):
        if self.theMainNode is not None:
            self.theMainNode.MainLoopProcess()
        self.theMainFrame.after(1000, self.update_MainLoop)

    def destroy(self):
        self.CBStopIcocube()
        pass

    def CBStopIcocube(self):
        if self.theMainNode is not None:
            self.theMainNode.stopNodeSystem()
        self.theMainNode = None
        self.BTStartIcocube.config(state="normal")
        self.BTStopIcocube.config(state="disable")


if __name__ == '__main__':
   # vp_start_gui()
    print("Hello world")
    ICO3StartIcocube.launch()
    pass


