# Imports
import tkinter as tk
from tkinter import *

class GUI:
    def __init__(self, master):
        self.master = master

        # GUI Config
        self.master.title("A simple GUI")
        # self.master.geometry("200x100")
        self.master.resizable(False, False)

        # create the sample data file
        self.str1 = """"""
        self.fout = open("chem_data.txt", "w")
        self.fout.write(self.str1)
        self.fout.close()
        
        # read the data file into a list
        self.fin = open("chem_data.txt", "r")
        self.chem_list = self.fin.readlines()
        self.fin.close()
        # strip the trailing newline char
        self.chem_list = [chem.rstrip() for chem in self.chem_list]

        self.create_gui_widgets()

    def create_gui_widgets(self):
        # create the listbox (note that size is in characters)
        self.listbox1 = tk.Listbox(self.master, width=50, height=6)
        self.listbox1.grid(row=0, column=0)
        
        # create a vertical scrollbar to the right of the listbox
        self.yscroll = tk.Scrollbar(command=self.listbox1.yview, orient=tk.VERTICAL)
        self.yscroll.grid(row=0, column=1, sticky=tk.N+tk.S)
        self.listbox1.configure(yscrollcommand=self.yscroll.set)
        
        # use entry widget to display/edit selection
        self.enter1 = tk.Entry(self.master, width=50, bg='yellow')
        self.enter1.insert(0, 'Click on an item in the listbox or add an item yourself')
        self.enter1.grid(row=1, column=0)
        # pressing the return key will update edited line
        self.enter1.bind('<Return>', self.set_list)
        # or double click left mouse button to update line
        self.enter1.bind('<Double-1>', self.set_list)
        # button to sort listbox
        self.button1 = tk.Button(self.master, text='Sort the listbox    ', command=self.sort_list)
        self.button1.grid(row=2, column=0, sticky=tk.W)
        # button to save the listbox's data lines to a file
        self.button2 = tk.Button(self.master, text='Save lines to file', command=self.save_list)
        self.button2.grid(row=3, column=0, sticky=tk.W)
        # button to add a line to the listbox
        self.button3 = tk.Button(self.master, text='Add entry text to listbox', command=self.add_item)
        self.button3.grid(row=2, column=0, sticky=tk.E)
        # button to delete a line from listbox
        self.button4 = tk.Button(self.master, text='Delete selected line     ', command=self.delete_item)
        self.button4.grid(row=3, column=0, sticky=tk.E)
        # load the listbox with data
        for item in self.chem_list:
            self.listbox1.insert(tk.END, item)
        
        # left mouse click on a list item to display selection
        self.listbox1.bind('<ButtonRelease-1>', self.get_list)

    def add_item(self):
        """
        add the text in the Entry widget to the end of the listbox
        """
        self.listbox1.insert(tk.END, self.enter1.get())

    def delete_item(self):
        """
        delete a selected line from the listbox
        """
        try:
            # get selected line index
            self.index = self.listbox1.curselection()[0]
            self.listbox1.delete(self.index)
        except IndexError:
            pass
    
    def get_list(self, event):
        """
        function to read the listbox selection
        and put the result in an entry widget
        """
        # get selected line index
        self.index = self.listbox1.curselection()[0]
        # get the line's text
        self.seltext = self.listbox1.get(self.index)
        # delete previous text in enter1
        self.enter1.delete(0, 50)
        # now display the selected text
        self.enter1.insert(0, self.seltext)

    def set_list(self, event):
        """
        insert an edited line from the entry widget
        back into the listbox
        """
        try:
            self.index = self.listbox1.curselection()[0]
            # delete old listbox line
            self.listbox1.delete(self.index)
        except IndexError:
            self.index = tk.END
        # insert edited item back into listbox1 at index
        self.listbox1.insert(self.index, self.enter1.get())

    def sort_list(self):
        """
        function to sort listbox items case insensitive
        """
        self.temp_list = list(self.listbox1.get(0, tk.END))
        self.temp_list.sort(key=str.lower)
        # delete contents of present listbox
        self.listbox1.delete(0, tk.END)
        # load listbox with sorted data
        for item in self.temp_list:
            self.listbox1.insert(tk.END, item)
            
    def save_list(self):
        """
        save the current listbox contents to a file
        """
        # get a list of listbox lines
        self.temp_list = list(self.listbox1.get(0, tk.END))
        # add a trailing newline char to each line
        self.temp_list = [chem + '\n' for chem in self.temp_list]
        # give the file a different name
        self.fout = open("chem_data2.txt", "w")
        self.fout.writelines(self.temp_list)
        self.fout.close()


root = Tk()
my_gui = GUI(root)
root.mainloop()