from functools import partial
import gradio as gr

from src.logic.data_fetching import fetch_groups, fetch_metrics, reverse_search, reverse_search_add

def create_reverse_search_tab(base_folder: gr.Textbox, datasets_available: gr.State, datasets_selected: gr.Dropdown):
    reverse_search_headline = gr.Markdown(value="# Reverse Metrics Search")

    with gr.Row():
        with gr.Column(scale=1):
            reverse_grouping_dropdown = gr.Dropdown(
                choices=[],
                label="Grouping",
                multiselect=False,
            )
            reverse_metric_name_dropdown = gr.Dropdown(
                choices=[],
                label="Metric Name",
                multiselect=False,
            )
            reverse_search_button = gr.Button("Search")
            reverse_search_add_button = gr.Button("Add to selection")

        with gr.Column(scale=2):
            reverse_search_results = gr.Textbox(
                label="Found datasets",
                lines=10,
                placeholder="Found datasets containing the group/metric name. You can modify the selection after search by removing unwanted lines and clicking Add to selection"
            )
            
    datasets_available.change(
        fn=partial(fetch_groups, type="union"),
        inputs=[base_folder, datasets_available, reverse_grouping_dropdown],
        outputs=[reverse_grouping_dropdown],
    )

    reverse_grouping_dropdown.select(
        fn=partial(fetch_metrics, type="union"),
        inputs=[base_folder, datasets_available, reverse_grouping_dropdown, reverse_metric_name_dropdown],
        outputs=reverse_metric_name_dropdown,
    )

    reverse_search_button.click(
        fn=partial(reverse_search),
        inputs=[base_folder, datasets_available, reverse_grouping_dropdown, reverse_metric_name_dropdown],
        outputs=reverse_search_results,
    )

    reverse_search_add_button.click(
        fn=reverse_search_add,
        inputs=[datasets_selected, reverse_search_results],
        outputs=datasets_selected,
    )