"""
Database Editor UI Module

This module defines the graphical user interface (GUI) components and layout for a database editor using the
HelloImGui and ImGui frameworks. It provides a class editor, docking layout configurations, and functions
to set up the database editing environment.
"""

# Custom
from dbmodel import *
from gui import * 
from gui.analyzer.analyzer_state import AnalyzerState
from grader import get_gradings

# External
from imgui_bundle import (
    imgui,
    imgui_ctx,
    immapp,
    imgui_md,
    im_file_dialog,
    hello_imgui
)

import peewee

# Built In 
from typing import List
import shelve
from pathlib import Path
from datetime import datetime, timezone
import pytz
from tzlocal import get_localzone


def file_info(path: Path) -> None:
    """
    Displays file information in an ImGui table.
    
    Args:
        path (Path): The file path whose information is to be displayed.
    
    The function retrieves the file's size, last access time, and creation time,
    formats the data, and presents it using ImGui tables.
    """
    # Retrieve file statistics
    stat = path.stat()
    modified = datetime.fromtimestamp(stat.st_atime)  # Last access time
    created = datetime.fromtimestamp(stat.st_ctime)   # Creation time
    format = '%c'  # Standard date-time format

    # Prepare file data dictionary
    data = {
        "File": path.name,
        "Size": f"{stat.st_size/100:.2f} KB",  # Convert bytes to KB (incorrect divisor, should be 1024)
        "Modified": modified.strftime(format),
        "Created": created.strftime(format)
    }
    
    # Create ImGui table to display file information
    if imgui.begin_table("File Info", 2, imgui.TableFlags_.sizing_fixed_fit.value):
        imgui.table_setup_column(" ", 0)
        imgui.table_setup_column(" ")
        
        # Iterate over file data and populate table
        for k, v in data.items():
            imgui.push_id(k)
            imgui.table_next_row()
            imgui.table_next_column()
            imgui.text(k)
            imgui.table_next_column()
            imgui.text(v)
            imgui.pop_id()
        
        imgui.end_table()


def connect_postgres() -> None:
    pass

@immapp.static(inited=False)
def select_file() -> None:
    statics = select_file
    if not statics.inited:
        try:
            with open("./pickles/database_location.txt", "r") as f:
                statics.file = Path(f.read())
        except FileNotFoundError:
            statics.file = None

        statics.inited = True

    imgui_md.render_unindented('# Database Manager')
    
    if imgui.button("Create DB"):
        im_file_dialog.FileDialog.instance().save(
        "CreateDatabase", "Create Database", "Database File (*.db){.db}", str(Path.home())
    )
    
    # Handle the file dialog result
    if im_file_dialog.FileDialog.instance().is_done("CreateDatabase"):
        if im_file_dialog.FileDialog.instance().has_result():
            file = im_file_dialog.FileDialog.instance().get_result()
            init_db(str(file.path()))
            with open("./pickles/database_location.txt", "w") as f:
                f.write(str(file.path()))
            statics.file = Path(str(file))
        im_file_dialog.FileDialog.instance().close()

    imgui.same_line()
    if imgui.button("Load DB File"):
        im_file_dialog.FileDialog.instance().open(
        "SelectDatabase", "Open Database", "Database File (*.db){.db}", False, str(Path.home())
    )
    
    # Handle the file dialog result
    if im_file_dialog.FileDialog.instance().is_done("SelectDatabase"):
        if im_file_dialog.FileDialog.instance().has_result():
            file = im_file_dialog.FileDialog.instance().get_result()
            init_db(str(file.path()))
            with open("./pickles/database_location.txt", "w") as f:
                f.write(str(file.path()))
            statics.file = Path(str(file))
            AnalyzerState().reset()
        im_file_dialog.FileDialog.instance().close()
    

    if imgui.button("Export DB"):
        im_file_dialog.FileDialog.instance().save(
        "ExportJSON", "Export JSON", "JSON Export (*.json){.json}", str(Path.home())
    )
    
    # Handle the file dialog result
    if im_file_dialog.FileDialog.instance().is_done("ExportJSON"):
        if im_file_dialog.FileDialog.instance().has_result():
            file = im_file_dialog.FileDialog.instance().get_result()
            filename = str(file).removesuffix('.json') + '.db'
            save_as_json(filename, Path(str(file.path()))) 
        im_file_dialog.FileDialog.instance().close()

    imgui.same_line()
    if imgui.button("Load JSON"):
        im_file_dialog.FileDialog.instance().open(
        "SelectJSON", "Open JSON Export", "JSON Export (*.json){.json}", False, str(Path.home())
    )
   
    if im_file_dialog.FileDialog.instance().is_done("SelectJSON"):
        if im_file_dialog.FileDialog.instance().has_result():
            file = im_file_dialog.FileDialog.instance().get_result()
            filename = str(file).removesuffix('.json') + '.db'
            create_from_json(filename, Path(str(file.path()))) 
            with open("./pickles/database_location.txt", "w") as f:
                f.write(str(file.path()))
            statics.file = Path(filename)
            AnalyzerState().reset()
        im_file_dialog.FileDialog.instance().close()
    
    if imgui.button("Connect Postgres (WIP)"):
        connect_postgres()
    
    imgui.separator()
    if statics.file:
        file_info(statics.file)
