from tkinter import filedialog, messagebox
from app.gui.model import Model
from app.gui.views import BaseView, ConfirmView, ImageView
from app.utils import form_logger


logger = form_logger("guiLogger")


class BaseController:
    def __init__(self):
        self.view = None

    def bind(self, view: BaseView):
        self.view = view
        self.view.create_view()


class InputController(BaseController):
    def __init__(self, model: Model):
        super().__init__()
        self.model = model

    def bind(self, view: BaseView):
        super().bind(view)
        self.set_default_inputs()
        self.view.buttons["select_folder"].configure(command=self.select_image_folder)
        self.view.buttons["clear_all_fields"].configure(command=self.set_default_inputs)
        self.view.buttons["proceed_to_images"].configure(command=self.view_images)

    def select_image_folder(self):
        for button in self.view.buttons.values():
            button.configure(state="disabled")
        folderPath = filedialog.askdirectory()
        for button in self.view.buttons.values():
            button.configure(state="enabled")
        self.view.var_image_folder_path.set(folderPath)

    def set_default_inputs(self):
        logger.info("gui fields cleared")
        self.view.var_intimation_no.set("")
        self.view.var_survey_conductor.set("")
        self.view.var_workshop_name.set("")
        self.view.var_workshop_contact.set("")
        self.view.var_image_folder_path.set("")
        self.view.var_depreciation.set("")
        self.view.var_replacement_cost.set("")
        self.view.var_net_payable.set("")
        self.view.var_extent_loss.set("MEDIUM")
        self.view.var_reported_by.set("BRANCH")
        self.view.var_parts_missing.set("NO")
        self.view.bool_payment.set(False)
        self.view.bool_part.set(False)
        self.view.bool_lumpsum.set(False)
        self.view.var_operation_type.set("Final Report")
        self.view.var_action_data.set(False)
        self.view.var_action_pictures.set(False)
        self.view.var_action_parts.set(False)
        self.view.var_upload_on.set("EFU Preliminary Report")

    def view_images(self):
        for button in self.view.buttons.values():
            button.configure(state="disabled")
        for dropdown in self.view.dropdowns.values():
            dropdown.configure(state="disabled")
        user_input = self.form_user_input()
        response = self.model.validate_user_input(user_input)
        if response.title != "VALID":
            logger.error(f"{response.message}")
            messagebox.showerror(title=response.title, message=response.message)
            for button in self.view.buttons.values():
                button.configure(state="enabled")
            for dropdown in self.view.dropdowns.values():
                dropdown.configure(state="enabled")
        else:
            logger.info("user input was validated")
            if user_input["action_pictures"] is False:
                confirm_controller = ConfirmController(self)
                confirm_controller.bind(ConfirmView(master=self.view))
            else:
                image_controller = ImageController(self)
                image_controller.bind(ImageView(master=self.view))

    def form_user_input(self):
        user_input_json = {
            "intimation_no": self.view.var_intimation_no.get(),
            "survey_conductor": self.view.var_survey_conductor.get(),
            "workshop_name": self.view.var_workshop_name.get(),
            "workshop_contact": self.view.var_workshop_contact.get(),
            "image_folder_path": self.view.var_image_folder_path.get(),
            "depreciation": self.view.var_depreciation.get(),
            "replacement_cost": self.view.var_replacement_cost.get(),
            "net_payable": self.view.var_net_payable.get(),
            "extent_of_loss": self.view.var_extent_loss.get(),
            "reported_by": self.view.var_reported_by.get(),
            "parts_missing": self.view.var_parts_missing.get(),
            "bill_type_payment": self.view.bool_payment.get(),
            "bill_type_part": self.view.bool_part.get(),
            "bill_type_lumpsum": self.view.bool_lumpsum.get(),
            "operation_type": self.view.var_operation_type.get(),
            "action_data": self.view.var_action_data.get(),
            "action_pictures": self.view.var_action_pictures.get(),
            "action_parts": self.view.var_action_parts.get(),
            "upload_on": self.view.var_upload_on.get(),
            "connection_location": self.view.var_connection_loc.get(),
        }
        logger.debug(f"formed user input: {user_input_json}")
        return user_input_json


class ImageController(BaseController):
    def __init__(self, parent: InputController):
        super().__init__()
        self.parent = parent
        self.model = parent.model
        self.image_index = 0

    def bind(self, view: BaseView):
        self.view = view
        self.view.create_view(
            image_names=self.model.user_input.image_names,
            initialized_images=self.model.user_input.initialized_images,
        )
        self.view.buttons["back"].configure(command=self.go_back)
        self.view.buttons["change_directory"].configure(command=self.change_directory)
        self.view.buttons["confirm_images"].configure(command=self.confirmed)
        self.view.buttons["forward"].configure(command=self.go_forward)

    def change_directory(self):
        logger.warning("changing image directory")
        self.view.master.destroy()
        for button in self.view.parent.buttons.values():
            button.configure(state="enabled")

    def go_forward(self):
        logger.debug("moving to next image")
        self.image_index += 1
        self.view.update_view(self.image_index)
        self.view.buttons["forward"].configure(command=self.go_forward)
        self.view.buttons["back"].configure(command=self.go_back)

    def go_back(self):
        logger.debug("moving to previous image")
        self.image_index -= 1
        self.view.update_view(self.image_index)
        self.view.buttons["forward"].configure(command=self.go_forward)
        self.view.buttons["back"].configure(command=self.go_back)

    def confirmed(self):
        # if not self.view.validation:
        #     logger.error("All images not viewed")
        #     messagebox.showerror(title="Error", message="Please view all images")
        # else:
        logger.info("Images confirmed")
        self.view.master.destroy()
        confirm_controller = ConfirmController(self.parent)
        confirm_controller.bind(ConfirmView(self.parent.view))


class ConfirmController(BaseController):
    def __init__(self, parent: InputController):
        super().__init__()
        self.parent = parent
        self.model = parent.model

    def bind(self, view: BaseView):
        self.view = view
        self.view.create_view(user_input=self.model.user_input)
        self.view.buttons["back"].configure(command=self.go_back)
        self.view.buttons["finish"].configure(command=self.finish)

    def go_back(self):
        logger.warning("final confirmation stopped")
        self.view.master.destroy()
        for button in self.view.parent.buttons.values():
            button.configure(state="enabled")

    def finish(self):
        logger.info(
            f"uploading for intimation no: {self.model.user_input.intimation_no}, image folder: {self.model.user_input.image_folder_path}, survey_conductor={self.model.user_input.survey_conductor}, workshop_name={self.model.user_input.workshop_name}, workshop_contact={self.model.user_input.workshop_contact}, depreciation={self.model.user_input.depreciation}, extent_of_loss={self.model.user_input.extent_of_loss}, reported_by={self.model.user_input.reported_by}, parts_missing={self.model.user_input.parts_missing}, bill_type:{self.model.user_input.bill_type}, replacement_cost={self.model.user_input.replacement_cost}, net_payable={self.model.user_input.net_payable}, operation_type={self.model.user_input.operation_type}\n"
        )
        messagebox.showwarning(
            title="Input Received", message="Automated bot uploading now"
        )
        self.model.bot_operation = True
        self.view.master.destroy()
        self.parent.view.master.destroy()
