# * Copyright (C) 2020 Texas Instruments Incorporated - http://www.ti.com/
#  *
#  *
#  *  Redistribution and use in source and binary forms, with or without
#  *  modification, are permitted provided that the following conditions
#  *  are met:
#  *
#  *    Redistributions of source code must retain the above copyright
#  *    notice, this list of conditions and the following disclaimer.
#  *
#  *    Redistributions in binary form must reproduce the above copyright
#  *    notice, this list of conditions and the following disclaimer in the
#  *    documentation and/or other materials provided with the
#  *    distribution.
#  *
#  *    Neither the name of Texas Instruments Incorporated nor the names of
#  *    its contributors may be used to endorse or promote products derived
#  *    from this software without specific prior written permission.
#  *
#  *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
#  *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
#  *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
#  *  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
#  *  OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
#  *  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
#  *  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
#  *  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
#  *  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
#  *  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
#  *  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#  *
# */

from Program_Callbacks import *


def resource_path(relative_path):
    if hasattr(sys, '_MEIPASS'):
        return os.path.join(sys._MEIPASS, relative_path)
    return os.path.join('r', os.path.abspath("."), relative_path)


def about(self):
    message = "Welcome to the Zigbee Network Properties Cloning Tool! This tool allows for the cloning of a coordinator \
within a ZigBee 3.0 Mesh Network using the SimpleLink CC1352P and CC2652R devices. The task is accomplished \
through the use of Python and the Monitor and Test (MT) Application Process Interface (API). For more information \
please refer to the Resources section."
    self.popup = tk.Toplevel()
    self.popup.title("About")
    position_right = int(self.popup.winfo_screenwidth() / 2 - self.popup.winfo_reqwidth() / 2) - 50
    position_down = int(self.popup.winfo_screenheight() / 2 - self.popup.winfo_reqheight() / 2) - 100
    self.popup.geometry("+{}+{}".format(position_right, position_down))
    self.popup.geometry("300x200")
    msg = tk.Message(self.popup, text=message, bg='white')
    msg.pack(expand=1, fill='both')
    if sys.platform.startswith('win'):
        image_icon = PhotoImage(file=resource_path("ti_logo.png"))
        self.popup.tk.call('wm', 'iconphoto', self.popup.w, image_icon)
    return


def resources(self):
    # Create the window for the 'Resources' tab
    self.res = tk.Toplevel(bg='white')
    position_right = int(self.res.winfo_screenwidth() / 2 - self.res.winfo_reqwidth() / 2) - 50
    position_down = int(self.res.winfo_screenheight() / 2 - self.res.winfo_reqheight() / 2) - 100
    self.res.geometry("+{}+{}".format(position_right, position_down))
    self.res.geometry("300x170")
    self.res.title("Resources")
    if sys.platform.startswith('win'):
        image_icon = PhotoImage(file=resource_path("ti_logo.png"))
        self.res.tk.call('wm', 'iconphoto', self.res.w, image_icon)

    # Fill the window with content
    link1 = tk.Label(self.res, text="For information on how this tool functions:", fg="black",
                     cursor='hand2', bg='white')
    link1.grid(row=0, column=0, sticky='w')
    link2 = tk.Label(self.res, text="Cloning Z-Stack Network Properties", fg="blue",
                     cursor='hand2', bg='white')
    link2.grid(row=1, column=0, sticky='w')
    link2.bind("<Button-1>", lambda e: url_callback("http://www.ti.com/lit/swra671"))
    link3 = tk.Label(self.res, text="To learn more about the MT API:", fg="black", cursor='hand2', bg='white')
    link3.grid(row=2, column=0, sticky='w')
    link4 = tk.Label(self.res, text="Z-Stack Monitor and Test API", fg="blue", cursor='hand2', bg='white')
    link4.grid(row=3, column=0, sticky='w')
    link4.bind("<Button-1>", lambda e: url_callback("http://dev.ti.com/tirex/explore/content/simplelink_"
                                                    "cc13x2_26x2_sdk_3_40_00_02/docs/zigbee/Z-Stack%20Monitor%20"
                                                    "and%20Test%20API.pdf"))
    link5 = tk.Label(self.res, text="Information about Zigbee Network Processors:", fg="black",
                     cursor='hand2', bg='white')
    link5.grid(row=4, column=0, sticky='w')
    link6 = tk.Label(self.res, text="Zigbee Network Processor (ZNP) Interface", fg="blue", cursor='hand2', bg='white')
    link6.grid(row=5, column=0, sticky='w')
    link6.bind("<Button-1>", lambda e: url_callback("http://dev.ti.com/tirex/explore/content/simplelink_cc13x2_26x2_sdk_4_10_00_78/docs/zigbee/html/zigbee/znp_interface.html#zigbee-network-processor-znp-interface"))
    link7 = tk.Label(self.res, text="Texas Instruments (Zigbee Page):", fg="black", cursor='hand2', bg='white')
    link7.grid(row=6, column=0, sticky='w')
    link8 = tk.Label(self.res, text="Zigbee Solutions", fg="blue", cursor='hand2', bg='white')
    link8.grid(row=7, column=0, sticky='w')
    link8.bind("<Button-1>", lambda e: url_callback("http://www.ti.com/wireless-connectivity/simplelink-solutions/zigbee/overview.html?keyMatch=ZIBGEE&tisearch=Search-EN-everything&usecase=generic"))
    return


def software(self):
    # Create the window for the 'Software' tab
    self.popup = tk.Toplevel(bg='white')
    position_right = int(self.popup.winfo_screenwidth() / 2 - self.popup.winfo_reqwidth() / 2) - 100
    position_down = int(self.popup.winfo_screenheight() / 2 - self.popup.winfo_reqheight() / 2) - 100
    self.popup.geometry("+{}+{}".format(position_right, position_down))
    self.popup.title("Software")
    if sys.platform.startswith('win'):
        self.popup.geometry("450x130")
        image_icon = PhotoImage(file=resource_path("ti_logo.png"))
        self.popup.tk.call('wm', 'iconphoto', self.popup.w, image_icon)
    else:
        self.popup.geometry("500x150")

    # Fill the window with content
    python_version = tk.Label(self.popup, text="Python Version: 3.7", fg='black', bg='white')
    python_version.grid(row=0, column=0, sticky='w')
    python_install = tk.Label(self.popup, text="To install Python click here", fg='blue', bg='white')
    python_install.grid(row=1, column=0, sticky='w')
    python_install.bind("<Button-1>", lambda e: url_callback("https://www.python.org/"))
    pys_version = tk.Label(self.popup, text="PySerial Version: 3.4", fg='black', bg='white')
    pys_version.grid(row=2, column=0, sticky='w')
    pys_api = tk.Label(self.popup, text="For the PySerial API click here", fg='blue', bg='white')
    pys_api.grid(row=3, column=0, sticky='w')
    pys_api.bind("<Button-1>", lambda e: url_callback("https://pypi.org/project/pyserial/"))
    sdk_version = tk.Label(self.popup, text="SimpleLink CC13X2 / CC26X2 SDK Version: 3.4", fg='black', bg='white')
    sdk_version.grid(row=4, column=0, sticky='w')
    sdk_info = tk.Label(self.popup, text="To obtain information about the Simplelink CC13x2/CC26x2 v3.4 SDK click here",
                        fg='blue', bg='white')
    sdk_info.grid(row=5, column=0, sticky='w')
    sdk_info.bind("<Button-1>", lambda e: url_callback("http://dev.ti.com/tirex/explore/node?node=AOSQDVXMohlV5LElLx5wxA__pTTHBmu__LATEST"))
    return


def how_to_use(self):
    # Open the URL in a browser
    webbrowser.open_new("http://www.ti.com/lit/swra671")
    return


def nv_index(self, desc_file):
    # Create the window for the 'NVM Regions' tab
    self.popup = tk.Toplevel(bg='white')
    self.popup.title("NVM Index")
    if sys.platform.startswith('win'):
        position_right = int(self.popup.winfo_screenwidth() / 2 - self.popup.winfo_reqwidth() / 2) - 290
        position_down = int(self.popup.winfo_screenheight() / 2 - self.popup.winfo_reqheight() / 2) - 190
        self.popup.geometry("+{}+{}".format(position_right, position_down))
        self.popup.geometry("900x490")
        image_icon = PhotoImage(file=resource_path("ti_logo.png"))
        self.popup.tk.call('wm', 'iconphoto', self.popup.w, image_icon)
    else:
        position_right = int(self.popup.winfo_screenwidth() / 2 - self.popup.winfo_reqwidth() / 2) - 320
        position_down = int(self.popup.winfo_screenheight() / 2 - self.popup.winfo_reqheight() / 2) - 200
        self.popup.geometry("+{}+{}".format(position_right, position_down))
        self.popup.geometry("1000x550")

    # Read the information from the Descriptions File
    content = []
    name = []
    desc = []
    with open(desc_file, 'r') as file:
        for line in file.readlines():
            line = ((line.strip('\n')).split(':'))
            for x in range(len(line)):
                line[x] = line[x].strip()
            if line[0] != '' and line[1] != '' and line[2] != '':
                content.append(line[0])
                name.append(line[1])
                desc.append(line[2])
    file.close()

    # Fill in the window with content
    for x in range(len(content)):
        if x == 0:
            lb = tk.Label(self.popup, text=content[x], font='Helvetica 10 bold', bg='white')
            lb.grid(row=x, column=0, sticky='w', padx=5, pady=5)
            lb = tk.Label(self.popup, text=name[x], font='Helvetica 10 bold', bg='white')
            lb.grid(row=x, column=1, sticky='w',  padx=5, pady=5)
            lb = tk.Label(self.popup, text=desc[x], font='Helvetica 10 bold', bg='white')
            lb.grid(row=x, column=2, sticky='w', padx=5, pady=5)
        else:
            lb = tk.Label(self.popup, text=content[x], bg='white')
            lb.grid(row=x, column=0, sticky='w', padx=5, pady=5)
            lb = tk.Label(self.popup, text=name[x], bg='white')
            lb.grid(row=x, column=1, sticky='w', padx=5, pady=5)
            lb = tk.Label(self.popup, text=desc[x], bg='white', wraplength=450, justify=LEFT)
            lb.grid(row=x, column=2, sticky='w', padx=5, pady=5)
    return
