import gradio as gr
import os 

from process import process_data 

def makeButtonClickableFiles(files):
    """Makes a button interactive only if all files in the list have correct extensions.

    Args:
        files (list): List of uploaded file objects.

    Returns:
        _type_: Button state (interactive or not) and possibly a warning message.
    """
    if not files:
        return gr.Button(interactive=False)
    
    allowed_extensions = ["xls", "xlsx"]
    for file in files:
        base_name = os.path.basename(file.name)
        # Extract the file extension and check if it's in the allowed list.
        if base_name.split('.')[-1].lower() not in allowed_extensions:
            raise gr.Error(f"Unsupported file: {base_name}.Allowed extensions: .xls .xlsx")

    return gr.Button(interactive=True)


# Define a Gradio interface

with gr.Blocks() as demo:

    with gr.Row(): 
        header = gr.Markdown(("<h1>MindBody VS. Medserv Checker </h1>"))
    
    with gr.Row():

        with gr.Column():
            file_uploader_mindbody = gr.Files(
            label=("Upload MindBody"),
            file_count="multiple",
            file_types=[".xlsx", '.xls'],
            container=True,
            interactive=True,
            scale=1,
            )        


        with gr.Column():
            file_uploader_medserv = gr.Files(
            label=("Upload Medserv"),
            file_count= "multiple",
            file_types=[".xlsx", '.xls'],
            container=True,
            interactive=True,
            scale=1,
        )
    
    with gr.Row():
        tollerance = gr.Slider(0, 7, value = 1, step = 1, interactive = True,  label="Days Tolerance", 
                  info="Set the number of days of tolerance to match the sale dates between MindBody and Medserve (0 = no tolerance / exact match).")

    with gr.Row():

        file_process_button = gr.Button(
        value="PROCESS FILES",
        interactive=False,
        )
    
    with gr.Row():
        processed_file = gr.Files(
        label=("Output File"),
        file_count="single",
        interactive=False,
        elem_classes="gradio-file",
    )




    file_uploader_mindbody.change(
                        fn=makeButtonClickableFiles, 
                        inputs=[file_uploader_mindbody], 
                        outputs=[file_process_button])

    
    file_uploader_medserv.change(
                        fn=makeButtonClickableFiles, 
                        inputs=[file_uploader_medserv], 
                        outputs=[file_process_button])
    
    
    file_process_button.click(
                        fn = process_data,
                        inputs = [file_uploader_mindbody, file_uploader_medserv, tollerance], 
                        outputs = processed_file)

                    
if __name__ == "__main__":
    demo.queue().launch()