# * 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 tkinter import *
from tkinter.filedialog import askopenfilename
import os
from os import path
import global_vars


def load_config(self):
    # Ask the user to select a file (Only allow text file)
    config_file = askopenfilename()
    if config_file != '':
        config_id_file = (config_file.strip('.txt') + '_ID') + '.txt'

        # Verify the paths are correct
        if os.path.exists(config_file) and os.path.exists(config_id_file):
            global_vars.id_file = config_id_file
            from Program_Callbacks import erase
            erase(self)

            # Open the file and read content
            with open(config_file, 'r') as f:
                lines = f.readlines()
                for x in range(len(lines)):

                    # Filter the content based on the row
                    if x == 0:  # Application Selection
                        self.v.set(int(lines[x]))

                    if x == 1:  # READ COM Port
                        line = ((lines[x].strip('\n')).split(':'))
                        items = self.Lb1.get(0, END)
                        for y in range(len(line)):
                            if line[y] != "":
                                self.Lb1.config(state=NORMAL)
                                self.Lb1.activate(items.index(line[y]))
                                self.Lb1.selection_set(items.index(line[y]))

                    if x == 2:  # WRITE COM Port
                        line = ((lines[x].strip('\n')).split(':'))
                        items = self.Lb2.get(0, END)
                        for y in range(len(line)):
                            if line[y] != "":
                                self.Lb2.config(state=NORMAL)
                                self.Lb2.activate(items.index(line[y]))
                                self.Lb2.selection_set(items.index(line[y]))

                    if x == 3:  # Write the READ Settings
                        line = ((lines[x].strip('\n')).split(':'))
                        items = self.Lb4.get(0, END)
                        for y in range(len(line)):
                            if line[y] != "":
                                self.Lb4.config(state=NORMAL, bd=0)
                                self.Lb4.activate(items.index(line[y]))
                                self.Lb4.selection_set(items.index(line[y]))

                    if x == 4:  # Write the Write Settings
                        line = ((lines[x].strip('\n')).split(':'))
                        if len(line) != 0:
                            # Enable the Frame
                            for m in self.fr_write_back.winfo_children():
                                m.config(state=NORMAL)
                            # Fill in the frame content
                            w_list = self.fr_write_back.winfo_children()
                            for y in range(len(line)):
                                for z in range(len(w_list)):
                                    if w_list[z].winfo_class() == 'Label':
                                        if w_list[z].cget("text") == line[y]:
                                            w_list[z + 1].insert(0, str(line[y + 1]))

                    if x == 6:  # Check the write from file option
                        line = ((lines[x].strip('\n')).split('*'))
                        if line[0] == '0':  # Not writing from a file
                            for y in self.fr_write_back.winfo_children():
                                y.config(state=NORMAL)
                            self.write_select.config(state=DISABLED)
                            self.w.set(0)

                        if line[0] == '1' and line[1] != ' ':  # Writing from a file
                            global_vars.content_file = line[1]
                            self.write_select.config(state=ACTIVE)
                            self.w.set(1)
                            for y in self.fr_write_back.winfo_children():
                                y.config(state=DISABLED)
                            self.write_file_label.config(state=NORMAL)
                            self.write_file_label.grid()

            f.close()
        else:
            if not path.exists(config_file):
                self.Lb3.insert('Could not find ' + os.path.basename(config_file))
            if not path.exists(config_id_file):
                self.Lb3.insert('Could not find ' + os.path.basename(config_id_file))
            self.Lb3.yview(END)
    return
