import PySimpleGUI as sg
import time
import csv
import os

data_file = 'task_data.csv'

def load_data():
    if os.path.exists(data_file):
        with open(data_file, 'r') as f:
            return list(csv.reader(f))
    return []

def save_data(data):
    with open(data_file, 'w') as f:
        csv.writer(f).writerows(data)

def format_data(entry):
    start, end, elapsed, task = entry
    return f"{task} | Start: {time.ctime(float(start))} | End: {time.ctime(float(end))} | Duration: {elapsed}s"

data = load_data()

layout1 = [
    [sg.Text("Task you're going to do"), sg.Input(key="task")],
    [sg.Button("Start tracking", key="track_btn")],
]
layout2 = [
    [sg.Listbox([format_data(entry) for entry in data], size=(60, 10), key="task_list")],
    [sg.Button("Delete all entries"), sg.Button("Export to CSV"), sg.Button("Import from CSV")],
]

layout = [[sg.TabGroup([[sg.Tab("Task Tracker", layout1), sg.Tab("Task Data", layout2)]])]]

window = sg.Window("Task Tracker", layout)
tracking = False
start_time = None

while True:
    event, values = window.read()

    if event == sg.WIN_CLOSED:
        break

    if event == "track_btn":
        if not tracking:
            task = values["task"]
            if not task:
                continue
            start_time = time.time()
            window["task"].update(disabled=True)
            window["track_btn"].update("Stop task")
        else:
            end_time = time.time()
            elapsed = round(end_time - start_time, 2)
            entry = [str(start_time), str(end_time), str(elapsed), task]
            data.append(entry)
            save_data(data)
            window["task_list"].update([format_data(e) for e in data])
            window["task"].update("", disabled=False)
            window["track_btn"].update("Start tracking")
        tracking = not tracking

    if event == "Delete all entries":
        data.clear()
        save_data(data)
        window["task_list"].update([])

    if event == "Export to CSV":
        save_data(data)

    if event == "Import from CSV":
        data = load_data()
        window["task_list"].update([format_data(e) for e in data])

window.close()