from datetime import datetime as dt

from PyQt5.QtWidgets import (QWidget, QPushButton, 
                             QMenuBar, QHBoxLayout, 
                             QVBoxLayout, QLabel, 
                             QDockWidget, QTabWidget,
                             QProgressBar, QAction,
                             QMainWindow, QGridLayout)
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QSizePolicy as QSP

from gui.settings_window import SystemSettings, OperatorSettings, FilterSettings
from gui.report_gui import ReportSettings
from base.base import PlotItems


class StartWidget(QWidget):

    def __init__(self) -> None:
        super().__init__()
        self._build_main_layout()

    def get_widget(self) -> QWidget:
        return self

    def _build_main_layout(self) -> None:
        self.resize(800,800)
        self.seeking_mode_btn = QPushButton("Real time folder scanning")
        self.seeking_mode_btn.setFixedWidth(350)
        self.raport_mode_btn = QPushButton("Raport editor")
        self.raport_mode_btn.setFixedWidth(350)
        self.client_mode_btn = QPushButton("Client trace processor")
        self.client_mode_btn.setFixedWidth(350)

        button_layout = QHBoxLayout()
        button_layout.setSpacing(2)
        button_layout.addWidget(self.seeking_mode_btn)
        button_layout.addWidget(self.raport_mode_btn)
        button_layout.addWidget(self.client_mode_btn)
        button_widget = QWidget()
        button_widget.setLayout(button_layout)

        mainLayout = QVBoxLayout()
        label = QLabel("Select work mode")
        label.setStyleSheet(
            """QLabel{
            color: #ffffff;
            font-size: 40px;
            font-weight: bold;
            font-family: "Segoe UI", sans-serif;
            }"""
            )
        mainLayout.addWidget(label, alignment=Qt.AlignCenter)
        mainLayout.addWidget(button_widget)
        self.setLayout(mainLayout)
        

class CustomStatusBar(QWidget):

    def __init__(self) -> None:
        super().__init__()
        self._build_status_bar()

    def get_widget(self) -> QWidget:
        return self
    
    def set_mode(self, msg:str = '') -> None:
        if not isinstance(msg, str): msg = str(msg)
        self._mode_label.setText(msg)
        self._mode_label.adjustSize()

    def set_note(self, msg:str = '') -> None:
        if not isinstance(msg, str): msg = str(msg)
        self._note_label.setText(msg)
        self._note_label.adjustSize()

    def set_progress(self, percent:int = 0) -> None:
        if not isinstance(percent, int): percent = 0
        elif percent < 0: percent = 0
        elif percent > 100: percent = 100
        self._progress_bar.setValue(percent)
        

    def _build_status_bar(self) -> None:
        # Создание пользовательского виджета для StatusBar
        note_layout = QHBoxLayout()
        note_layout.setContentsMargins(10, 1, 10, 1) 
        note_layout.setSpacing(15)  # Устанавливаем расстояние между элементами
        
        # Создание QLabel и QProgressBar
        self._mode_label = QLabel()
        self._note_label = QLabel()
        self._progress_bar = QProgressBar()
        self._progress_bar.setRange(0, 100)
        self._progress_bar.setValue(0)
        self._progress_bar.setMinimumWidth(250)
        self._progress_bar.setMaximumHeight(10)
        self._progress_bar.setTextVisible(False)

        # Установка политики размеров
        self._mode_label.setSizePolicy(QSP.Policy.Preferred, QSP.Policy.Preferred)
        self._note_label.setSizePolicy(QSP.Policy.MinimumExpanding, QSP.Policy.Preferred)
        self._progress_bar.setSizePolicy(QSP.Policy.Fixed, QSP.Policy.Preferred)
        
        # Добавление виджетов в макет
        note_layout.addWidget(self._progress_bar)
        note_layout.addWidget(self._note_label)
        note_layout.addStretch(1)
        note_layout.addWidget(self._mode_label)

        self.setLayout(note_layout)
        self.setSizePolicy(QSP.Policy.Expanding, QSP.Policy.Preferred)


class CustomTabWidget(QTabWidget):

    def __init__ (self):
        super().__init__()
        self._build_tab_widget()
    
    def get_widget(self) -> QWidget:
        return self

    def _build_tab_widget(self) -> None:
        self.setTabsClosable(True)
        self.tabCloseRequested.connect(self.close_tab)
    
    #TODO: переписать обмен данными, засунуть ссылки куда-то еще
    def create_tab(self, plot_widget:QWidget) -> None:
        plot_items:PlotItems = plot_widget.property("pyqt_container")
        tab = QWidget()
        tab.setProperty("reg_items", plot_items.regions) 
        tab.setProperty("curve_items", plot_items.curves)
        tab.setProperty("qt_items", plot_items.qt_items) 
        grid = QGridLayout()
        grid.addWidget(plot_widget)
        tab.setLayout(grid)
        self.addTab(tab, "SF_trace_" + dt.now().strftime('%Y_%m_%d-%H_%M_%S'))
        self.setCurrentWidget(tab)

    def close_tab(self, index:int) -> None:
        if self.count() > index and index >= 0:
            self.removeTab(index)


class CustomMenuBar(QMenuBar):

    def __init__(self, 
                 operSettings:OperatorSettings,
                 sysSettings:SystemSettings,
                 repSettings:ReportSettings,
                 filterSettings:FilterSettings) -> None:
        super().__init__()
        self._operSettings = operSettings
        self._sysSettings = sysSettings
        self._repSettings = repSettings
        self._filterSettings = filterSettings
        self._build_dock_widgets()
        self._build_menu()
        
    def get_widget(self) -> QWidget:
        return self
    
    def setup(self, parent:QMainWindow) -> None:
        parent.addDockWidget(Qt.RightDockWidgetArea, self._operator_dock)
        parent.addDockWidget(Qt.RightDockWidgetArea, self._system_dock)
        parent.addDockWidget(Qt.RightDockWidgetArea, self._report_dock)
        parent.addDockWidget(Qt.RightDockWidgetArea, self._filter_dock)
        parent.setMenuBar(self)
    
    def _build_dock_widgets(self) -> None:
        """
        Инициализация док-виджетов для настроек.
        """
        # Создаем док-виджет для OperatorSettings
        self._operator_dock = QDockWidget("Operator Settings", self)
        self._operator_dock.setWidget(self._operSettings)
        self._operator_dock.setObjectName("OperatorSettings")
        self._operator_dock.hide()  # Скрываем по умолчанию

        # Создаем док-виджет для SystemSettings
        self._system_dock = QDockWidget("System Settings", self)
        self._system_dock.setWidget(self._sysSettings)
        self._system_dock.setObjectName("SystemSettings")
        self._system_dock.hide()  # Скрываем по умолчанию

        # Создаем док-виджет для ReportSettings
        self._report_dock = QDockWidget("View settings", self)
        self._report_dock.setWidget(self._repSettings)
        self._report_dock.setObjectName("ReportSettings")
        self._report_dock.hide()  # Скрываем по умолчанию

        # Создаем док-виджет для filterSettings
        self._filter_dock = QDockWidget("Filter settings", self)
        self._filter_dock.setWidget(self._filterSettings)
        self._filter_dock.setObjectName("FilterSetting")
        self._filter_dock.hide()  # Скрываем по умолчанию

        # Настройка док-виджетов
        self._set_dock_features(self._operator_dock)
        self._set_dock_features(self._system_dock)
        self._set_dock_features(self._report_dock)
        self._set_dock_features(self._filter_dock)

    def _build_menu(self) -> None:
        """
        Инициализация главного меню.
        """
        # Создаем меню "Режимы"
        modes_menu = self.addMenu("Mode")
        settings_menu = self.addMenu("Settings")

        # Создаем действия для меню
        self.seeking_action = QAction("Real time folder scanning", self)
        self.raport_action = QAction("Raport editor", self)
        self.client_action = QAction("Client trace processor", self)

        system_settings = QAction("System settings", self)
        system_settings.setIcon(QIcon('resources/system_ico.png'))
        system_settings.triggered.connect(lambda: self._toggle_visibility(self._system_dock))

        operator_settings = QAction("Operator settings ", self)
        operator_settings.setIcon(QIcon('resources/operator_ico.png'))
        operator_settings.triggered.connect(lambda: self._toggle_visibility(self._operator_dock))

        self.view_settings = QAction("View settings", self)
        self.view_settings.setIcon(QIcon('resources/view_ico.png'))
        self.view_settings.triggered.connect(lambda: self._toggle_visibility(self._report_dock))

        self.filter_settings = QAction("Filter settings", self)
        #self.filter_settings.setIcon(QIcon('resources/view_ico.png'))
        self.filter_settings.triggered.connect(lambda: self._toggle_visibility(self._filter_dock))

        # Добавляем действия в меню "Режимы"
        modes_menu.addAction(self.seeking_action)
        modes_menu.addAction(self.raport_action)
        modes_menu.addAction(self.client_action)

        settings_menu.addAction(system_settings)
        settings_menu.addAction(operator_settings)
        settings_menu.addAction(self.view_settings)
        settings_menu.addAction(self.filter_settings)

    def _toggle_visibility(self, body:QDockWidget = None) -> None:
        """
        Переключение видимости док-виджета.
        """
        if body:
            is_visible = body.isVisible()
            body.setVisible(not is_visible)

    @staticmethod
    def _set_dock_features(body:QDockWidget = None) -> None:
        """
        Настройка флагов док-виджета.
        """
        if body:
            flag_move = QDockWidget.DockWidgetMovable
            flag_close = QDockWidget.DockWidgetClosable
            flag_floating = QDockWidget.DockWidgetFloatable
            body.setFeatures(flag_move | flag_close | flag_floating)


class RaportWidget(QWidget):

    def __init__(self, tabWidget:CustomTabWidget):
        super().__init__()
        self._tabWidget = tabWidget
        self._build_widget()

    def get_widget(self) -> QWidget:
        return self

    def _build_widget(self):
        main_layout = QVBoxLayout()    
        self.save_screen_btn = QPushButton("Save state")
        self.save_screen_btn.setFixedWidth(185)
        self.open_file_btn = QPushButton("Open file")
        self.open_file_btn.setFixedWidth(185)

        button_layout = QHBoxLayout()
        button_layout.setSpacing(2)

        button_layout.addWidget(self.save_screen_btn)
        button_layout.addWidget(self.open_file_btn)
        button_widget = QWidget()
        button_widget.setLayout(button_layout)

        main_layout.addWidget(self._tabWidget)
        main_layout.addWidget(button_widget)
        self.setLayout(main_layout)


class SeekingWidget(QWidget):

    def __init__(self, tabWidget:CustomTabWidget):
        super().__init__()
        self._tabWidget = tabWidget
        self._build_widget()
        
    def get_widget(self) -> QWidget:
        return self

    def _build_widget(self):
        main_layout = QVBoxLayout()    
        button_layout = QHBoxLayout()
        button_layout.setSpacing(2)
        button_widget = QWidget()
        button_widget.setLayout(button_layout)
        
        main_layout.addWidget(self._tabWidget)
        main_layout.addWidget(button_widget)
        self.setLayout(main_layout)
        

class ClientAnalyzerWidget(QWidget):

    def __init__(self, tabWidget:CustomTabWidget):
        super().__init__()
        self._tabWidget = tabWidget
        self._build_widget()

    def get_widget(self) -> QWidget:
        return self

    def _build_widget(self):
        main_layout = QVBoxLayout()    
        self.save_screen_btn = QPushButton("Save state")
        self.save_screen_btn.setFixedWidth(185)
        self.open_folder_btn = QPushButton("Open folder")
        self.open_folder_btn.setFixedWidth(185)
        self.build_TCW_btn = QPushButton("Calculate TCW")
        self.build_TCW_btn.setFixedWidth(185)

        button_layout = QHBoxLayout()
        button_layout.setSpacing(2)

        button_layout.addWidget(self.save_screen_btn)
        button_layout.addWidget(self.open_folder_btn)
        button_layout.addWidget(self.build_TCW_btn)
        button_widget = QWidget()
        button_widget.setLayout(button_layout)

        main_layout.addWidget(self._tabWidget)
        main_layout.addWidget(button_widget)
        self.setLayout(main_layout)            
    