from datetime import datetime as dt
from typing import Optional

from PyQt5 import QtWidgets
from PyQt5.QtCore import Qt
from src.utils.base.base import BaseMainWindow, BaseController
from src.gui.settings_window import settingsWindow

class MainWindow(BaseMainWindow):
    def __init__(self, 
                 controller: Optional[BaseController] = None):
        super().__init__()
        self._controller = controller
        self.initUI()
        self.set_style(self)
        self.settings_button.clicked.connect(self._show_settings)
        self.operSettings = settingsWindow("params\operator_params.json", 'Operator', self._updater_trigger)
        self.sysSettings = settingsWindow("params\system_params.json", 'System', self._updater_trigger)

    def initUI(self) -> None:
        self.tabWidget = QtWidgets.QTabWidget()
        self.tabWidget.setTabsClosable(True)
        self.tabWidget.tabCloseRequested.connect(self._close_tab)
        layout = QtWidgets.QVBoxLayout()
        layout.addWidget(self.tabWidget)
        self.settings_button = QtWidgets.QPushButton("Show settings")
        self.settings_button.setFixedWidth(160)
        layout.addWidget(self.settings_button)
        self.setLayout(layout)

    def show_plot_tabs(self, plot_widgets: list[QtWidgets.QWidget]) -> None:
        for plot_widget in plot_widgets:
            tab = QtWidgets.QWidget()
            grid = QtWidgets.QGridLayout()
            grid.addWidget(plot_widget)
            tab.setLayout(grid)
            self.tabWidget.addTab(tab, "SF_trace_" + dt.now().strftime('%Y_%m_%d-%H_%M_%S'))
            self.tabWidget.setCurrentWidget(tab)

        tab_count = self.tabWidget.count()
        if tab_count > 10:
            for i in range(0, tab_count-2):
                self._close_tab(i)


    def keyPressEvent(self, a0):
        if a0.key() == Qt.Key_F5:
            pass

    def _show_settings(self):
        self.operSettings.show()
        self.sysSettings.show()
    
    def push_settings(self) -> None:
        self._updater_trigger()

    def _updater_trigger(self) -> None:
        self.tabWidget.clear()
        operator_params = self.operSettings.getParams()
        system_params = self.sysSettings.getParams()
        self._controller.push_settings([operator_params, system_params])
        
    def _close_tab(self, index:int) -> None:
        self.tabWidget.removeTab(index)
    



