import sys
import tkinter as tk
from tkinter import ttk, messagebox
import xml.etree.ElementTree as ET


file_path = '../XML/vasprun.xml'
window_size = '800x600'

nargs = len(sys.argv)
if nargs >= 2:
    file_path = sys.argv[1]
if nargs >= 3:
    window_size = sys.argv[2]


class XMLViewerEditor:
    def __init__(self, root, file_path, window_size):
        self.root = root
        self.root.title("XML Viewer and Editor")
        self.root.geometry(window_size)

        self.tree = ttk.Treeview(self.root, columns=("Value"))
        self.tree.heading('#0', text='Element')
        self.tree.heading('Value', text='Value')
        self.tree.pack(fill='both', expand=True)

        self.load_xml(file_path)

        self.tree.bind("<Double-1>", self.edit_cell)

    def load_xml(self, file_path):
        try:
            tree = ET.parse(file_path)
            self.root_element = tree.getroot()
            self.display_element(self.root_element, "")
        except ET.ParseError as e:
            print("Error:", str(e))

    def display_element(self, element, parent_id):
        item = self.tree.insert(parent_id, "end", text=element.tag, values=(element.text,))
        for key, value in element.attrib.items():
            self.tree.insert(item, "end", text=f"{key}: {value}")
        for child in element:
            self.display_element(child, item)

    def edit_cell(self, event):
        item = self.tree.selection()[0]
        col = self.tree.identify_column(event.x)
        print(f"edit col {col}")
        if col == '#1':  # Check if the user clicked on the 'Value' column
#        if col == '#2':  # Check if the user clicked on the 'Value' column
            self.tree.item(item, values=(self.tree.item(item, 'Value'),), open=True)
            self.tree.focus(item, "Value")
            self.tree.selection_set(item, "Value")
            self.tree.item(item, open=True)

if __name__ == "__main__":
    root = tk.Tk()
    app = XMLViewerEditor(root, file_path, window_size)
    root.mainloop()