from PyQt5.QtWidgets import QTabWidget, QGraphicsView, QFileDialog
from lrm.exceptions import lrm_slot, lrm_slot_param
import json


class Tabs:
    def __init__(self) -> None:
        self.create_tab_view()
        self.save_screen_button()
        self.save_all_screens_button()
        self.folder_name = None
    
    @lrm_slot_param
    def add_tab(self, tab_name):
        self.parent.tab_widget.addTab(QTabWidget(), tab_name)

        # Always display the last added tab
        self.parent.tab_widget.setCurrentIndex(self.parent.tab_widget.count() - 1)
        self.current_tab = self.parent.tab_widget.currentIndex()

        # Hide button for new tabs (because there's no rectangles yet)
        self.call_update_save()

    # This function is for keeping track which tab is open.
    @lrm_slot_param
    def handle_tabbar_clicked(self, index):
        self.current_tab = index
        self.current_tab_draw = self.parent.tab_widget.widget(self.current_tab)
        self.graphics_view = self.current_tab_draw.findChild(QGraphicsView)
        self.graphics_scene = self.graphics_view.scene()
        self.call_update_save()

    # This fucntion creates the tab inside the tab window that is specified in .ui layout.
    @lrm_slot
    def create_tab_view(self):
        self.parent.tab_widget.clear()
        self.parent.tab_widget.tabCloseRequested.connect(self.close_tab)
        self.parent.tab_widget.tabBarClicked.connect(self.handle_tabbar_clicked)

    @lrm_slot_param
    def close_tab(self, index):
        # Get the text of the tab that is being closed
        closed_tab_text = self.parent.tab_widget.tabText(index)

        # Set the current tab index to the index of the next tab, if it exists, or to None
        num_tabs = self.parent.tab_widget.count()
        if num_tabs == 1:
            self.current_tab_index = None
        elif index == num_tabs - 1:
            self.current_tab_index = index - 1
        else:
            self.current_tab_index = index + 1

        # remove the tab from the tab widget
        self.parent.tab_widget.removeTab(index)

        # Remove the rectangles, if they exist
        if self.current_tab in self.rectangles:
            del self.rectangles[self.current_tab]
        self.call_update_save()

    @lrm_slot
    def save_screen_button(self):
        self.parent.save_screen_button.setVisible(False)
        self.parent.save_screen_button.clicked.connect(self.save_results)
    
    @lrm_slot
    def save_all_screens_button(self):
        self.parent.save_all_screens_button.setVisible(False)
        self.parent.save_all_screens_button.clicked.connect(self.save_all_results)
    
    @lrm_slot
    def save_screen_button_updated(self):
        if self.current_tab in self.rectangles:
            self.parent.save_screen_button.setVisible(True)
        else:
            self.parent.save_screen_button.setVisible(False)

    @lrm_slot
    def save_all_screens_button_updated(self):
        if self.parent.tab_widget.count() > 1:
            if len(self.rectangles) > 1:
                self.parent.save_all_screens_button.setVisible(True)
        else:
            self.parent.save_all_screens_button.setVisible(False)

    @lrm_slot
    def call_update_save(self):
        self.save_screen_button_updated()
        self.save_all_screens_button_updated()

    @lrm_slot
    def save_results(self):
        # Remove star from the end of the tab name in order to display that it has been saved!
        self.remove_star_from_tab_name(self.current_tab)
        
        existing_data = []

        # Append the new dictionary to the existing data
        for current_tab in self.rectangles:
            if current_tab == self.current_tab:
                for item in self.rectangles[current_tab]:
                    existing_data.append(item.dialog_window.elements)
                break

        if self.folder_name is not None:
            # Write the data to the json file
            with open(f"{self.folder_name}/{self.parent.tab_widget.tabText(self.current_tab)}.json", "w") as scrn:
                json.dump(existing_data, scrn, indent=4)
        else:
            options = QFileDialog.Options()
            options |= QFileDialog.DontUseNativeDialog
            file_name = QFileDialog.getExistingDirectory(self.parent, "Select Directory")
            if file_name:
                self.folder_name = file_name
                # Write the data to the json file
                with open(f"{self.folder_name}/{self.parent.tab_widget.tabText(self.current_tab)}.json", "w") as scrn:
                    json.dump(existing_data, scrn, indent=4)
    
    @lrm_slot
    def save_all_results(self):
        existing_data = []

        # Append the new dictionary to the existing data
        for current_tab in self.rectangles:
    
            # # Remove star from the end of the tab name in order to display that it has been saved!
            self.remove_star_from_tab_name(current_tab)
            
            # Append data to be able to save them later to json.
            for item in self.rectangles[current_tab]:
                existing_data.append(item.dialog_window.elements)

            # Write the data to the json file
            with open(f"{self.parent.tab_widget.tabText(current_tab)}.json", "w") as scrn:
                json.dump(existing_data, scrn, indent=4)
            existing_data = []

    @lrm_slot_param
    def remove_star_from_tab_name(self, current_tab):
        # Remove star from the end of the tab name in order to display that it has been saved!
        if "*" == self.parent.tab_widget.tabText(current_tab)[-1]:
            tab_name = self.parent.tab_widget.tabText(current_tab)
            tab_name = tab_name.replace("*", "")
            self.parent.tab_widget.setTabText(current_tab, tab_name)
