import dearpygui.dearpygui as dpg

from utils import show_message, get_config_file_path, delete_config_items_and_clear_aliases, update_config_values, get_config, update_config_values, set_main_window_value, change_color_temporarily, path_iter

from style_constants import SPACE, COLLAPSING_HEADERS_UI
from style import get_accent_color, apply_theme
from config import load_config, dump_config, ConfigParserError
from dynamic_ui import construct_config_ui, construct_model_output_structure_ui

def set_file_path_clb(s, a, u):
    file_path = a['file_path_name']
    dpg.set_value(u, file_path)

def construct_config_ui_clb(s, a, u):
    if not get_config_file_path():
        return

    delete_config_items_and_clear_aliases()
    update_config_values()
    construct_config_ui(get_config_file_path(), get_config())

def config_save_as_clb(s, a, u):
    update_config_values()
    dump_config(get_config(), a['file_path_name'])
    show_message('file saved successfully:)')

def config_open_clb(s, a, u):
    delete_config_items_and_clear_aliases()
    config_file_path = a['file_path_name']

    try:
        config = load_config(config_file_path)
    except OSError:
        show_message('no file found')
        return
    except ConfigParserError:
        show_message('bad file format')
        return

    set_main_window_value('config', config)
    set_main_window_value('config_file_path', config_file_path)
    construct_config_ui(config_file_path, config)

def config_save_clb(s, a, u):
    update_config_values()
    dump_config(get_config(), get_config_file_path())
    show_message('file saved successfully:)')

def open_config_open_dialog_clb(s, a, u):
    dpg.show_item('config_open')

def show_config_search_window_clb(s, a, u):
    dpg.show_item('search_popup')

def open_config_save_as_dialog_clb(s, a, u):
    dpg.show_item('config_open')

def search_clb(s, data, u):
    if not get_config_file_path():
        return

    if not data:
        return

    for path in get_config():
        if data.lower() in path.split('.')[-1]:
            dpg.set_y_scroll('main', dpg.get_item_pos('.'.join([get_config_file_path(), path.split('.')[0]]))[1])
            for tag in path_iter(path, prefix=get_config_file_path()):
                if dpg.get_value(COLLAPSING_HEADERS_UI) == True:
                    dpg.set_value(tag, True)
                else:
                    dpg.set_value(dpg.get_item_parent(dpg.get_item_parent(tag)), dpg.get_item_parent(tag))
            change_color_temporarily('.'.join([get_config_file_path(), path, 'text']), color=get_accent_color())

def apply_theme_clb(s, a, u):
    apply_theme(s)