"""@package docstring
B-ASIC GUI Module.
This python file is the main window of the GUI for B-ASIC.
"""

from pprint import pprint
from os import getcwd, path
import logging
logging.basicConfig(level=logging.INFO)
import sys

from about_window import AboutWindow, FaqWindow, KeybindsWindow
from drag_button import DragButton
from gui_interface import Ui_main_window
from arrow import Arrow
from port_button import PortButton
from show_pc_window import ShowPCWindow

from b_asic import Operation, SFG, InputPort, OutputPort
from b_asic.simulation import Simulation
import b_asic.core_operations as c_oper
import b_asic.special_operations as s_oper
from utils import decorate_class, handle_error
from simulate_sfg_window import SimulateSFGWindow, Plot

from numpy import linspace

from PySide2.QtWidgets import QApplication, QWidget, QMainWindow, QLabel, QAction,\
QStatusBar, QMenuBar, QLineEdit, QPushButton, QSlider, QScrollArea, QVBoxLayout,\
QHBoxLayout, QDockWidget, QToolBar, QMenu, QLayout, QSizePolicy, QListWidget,\
QListWidgetItem, QGraphicsView, QGraphicsScene, QShortcut, QGraphicsTextItem,\
QGraphicsProxyWidget, QInputDialog, QTextEdit
from PySide2.QtCore import Qt, QSize
from PySide2.QtGui import QIcon, QFont, QPainter, QPen, QBrush, QKeySequence

MIN_WIDTH_SCENE = 600
MIN_HEIGHT_SCENE = 520

@decorate_class(handle_error)
class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.ui = Ui_main_window()
        self.ui.setupUi(self)
        self.setWindowIcon(QIcon('small_logo.png'))
        self.scene = None
        self._operations_from_name = dict()
        self.zoom = 1
        self.sfg_name_i = 0
        self.operationDict = dict()
        self.operationItemSceneList = []
        self.signalList = []
        self.pressed_operations = []
        self.portDict = dict()
        self.signalPortDict = dict()
        self.pressed_ports = []
        self.sfg_list = []
        self._window = self
        self.logger = logging.getLogger(__name__)
        self.init_ui()
        self.add_operations_from_namespace(c_oper, self.ui.core_operations_list)
        self.add_operations_from_namespace(s_oper, self.ui.special_operations_list)

        self.shortcut_core = QShortcut(QKeySequence("Ctrl+R"), self.ui.operation_box)
        self.shortcut_core.activated.connect(self._refresh_operations_list_from_namespace)
        self.shortcut_select_all = QShortcut(QKeySequence("Ctrl+A"), self.graphic_view)
        self.shortcut_select_all.activated.connect(self._select_all_operations)
        self.scene.selectionChanged.connect(self._select_operations)

        self.move_button_index = 0
        self.is_show_names = True

        self.check_show_names = QAction("Show operation names")
        self.check_show_names.triggered.connect(self.view_operation_names)
        self.check_show_names.setCheckable(True)
        self.check_show_names.setChecked(1)
        self.ui.view_menu.addAction(self.check_show_names)

        self.ui.actionShowPC.triggered.connect(self.show_precedence_chart)
        self.ui.actionSimulateSFG.triggered.connect(self.simulate_sfg)
        self.ui.faqBASIC.triggered.connect(self.display_faq_page)
        self.ui.aboutBASIC.triggered.connect(self.display_about_page)
        self.ui.keybindsBASIC.triggered.connect(self.display_keybinds_page)
        self.shortcut_help = QShortcut(QKeySequence("Ctrl+?"), self)
        self.shortcut_help.activated.connect(self.display_faq_page)

        self.logger.info("Finished setting up GUI")
        self.logger.info("For questions please refer to 'Ctrl+?', or visit the 'Help' section on the toolbar.")

    def init_ui(self):
        self.ui.core_operations_list.itemClicked.connect(self.on_list_widget_item_clicked)
        self.ui.special_operations_list.itemClicked.connect(self.on_list_widget_item_clicked)
        self.ui.exit_menu.triggered.connect(self.exit_app)
        self.create_toolbar_view()
        self.create_graphics_view()

    def create_graphics_view(self):
        self.scene = QGraphicsScene(self)
        self.graphic_view = QGraphicsView(self.scene, self)
        self.graphic_view.setRenderHint(QPainter.Antialiasing)
        self.graphic_view.setGeometry(self.ui.operation_box.width(), 20, self.width(), self.height())
        self.graphic_view.setDragMode(QGraphicsView.RubberBandDrag)

    def create_toolbar_view(self):
        self.toolbar = self.addToolBar("Toolbar")
        self.toolbar.addAction("Create SFG", self.create_SFG_from_toolbar)

    def resizeEvent(self, event):
        self.ui.operation_box.setGeometry(10, 10, self.ui.operation_box.width(), self.height())
        self.graphic_view.setGeometry(self.ui.operation_box.width() + 20, 30, self.width() - self.ui.operation_box.width() - 20, self.height()-30)
        super(MainWindow, self).resizeEvent(event)

    def wheelEvent(self, event):
        if event.modifiers() == Qt.ControlModifier:
            old_zoom = self.zoom
            self.zoom += event.angleDelta().y()/2500
            self.graphic_view.scale(self.zoom, self.zoom)
            self.zoom = old_zoom

    def view_operation_names(self):
        if self.check_show_names.isChecked():
            self.is_show_names = True
        else:
            self.is_show_names = False

        for operation in self.operationDict.keys():
            operation.label.setOpacity(self.is_show_names)
            operation.is_show_name = self.is_show_names

    def exit_app(self):
        self.logger.info("Exiting the application.")
        QApplication.quit()

    def create_SFG_from_toolbar(self):
        inputs = []
        outputs = []
        for op in self.pressed_operations:
            if isinstance(op.operation, s_oper.Input):
                inputs.append(op.operation)
            elif isinstance(op.operation, s_oper.Output):
                outputs.append(op.operation)

        name = QInputDialog.getText(self, "Create SFG", "Name: ", QLineEdit.Normal)
        self.logger.info(f"Creating SFG with name: {name[0]} from selected operations.")

        sfg = SFG(inputs=inputs, outputs=outputs, name=name[0])
        self.logger.info(f"Created SFG with name: {name[0]} from selected operations.")

        for op in self.pressed_operations:
            op.setToolTip(sfg.name)
        self.sfg_list.append(sfg)

    def show_precedence_chart(self):
        self.dialog = ShowPCWindow(self)
        self.dialog.add_sfg_to_dialog()
        self.dialog.show()

    def _determine_port_distance(self, length, ports):
        """Determine the distance between each port on the side of an operation.
        The method returns the distance that each port should have from 0.
        """
        return [length / 2] if ports == 1 else linspace(0, length, ports)

    def add_ports(self, operation):
        _output_ports_dist = self._determine_port_distance(55 - 17, operation.operation.output_count)
        _input_ports_dist = self._determine_port_distance(55 - 17, operation.operation.input_count)
        self.portDict[operation] = list()

        for i, dist in enumerate(_input_ports_dist):
            port = PortButton(">", operation, operation.operation.input(i), self)
            self.portDict[operation].append(port)
            operation.ports.append(port)
            port.move(0, dist)
            port.show()

        for i, dist in enumerate(_output_ports_dist):
            port = PortButton(">", operation, operation.operation.output(i), self)
            self.portDict[operation].append(port)
            operation.ports.append(port)
            port.move(55 - 12, dist)
            port.show()

    def get_operations_from_namespace(self, namespace):
        self.logger.info(f"Fetching operations from namespace: {namespace.__name__}.")
        return [comp for comp in dir(namespace) if hasattr(getattr(namespace, comp), "type_name")]

    def add_operations_from_namespace(self, namespace, _list):
        for attr_name in self.get_operations_from_namespace(namespace):
            attr = getattr(namespace, attr_name)
            try:
                attr.type_name()
                item = QListWidgetItem(attr_name)
                _list.addItem(item)
                self._operations_from_name[attr_name] = attr
            except NotImplementedError:
                pass

        self.logger.info(f"Added operations from namespace: {namespace.__name__}.")

    def _create_operation(self, item):
        self.logger.info(f"Creating operation of type: {item.text()}.")
        try:
            attr_oper = self._operations_from_name[item.text()]()
            attr_button = DragButton(attr_oper.graph_id, attr_oper, attr_oper.type_name().lower(), True, self)
            attr_button.move(250, 100)
            attr_button.setFixedSize(55, 55)
            attr_button.setStyleSheet("background-color: white; border-style: solid;\
            border-color: black; border-width: 2px")
            self.add_ports(attr_button)

            icon_path = path.join("operation_icons", f"{attr_oper.type_name().lower()}.png")
            if not path.exists(icon_path):
                icon_path = path.join("operation_icons", f"custom_operation.png")
            attr_button.setIcon(QIcon(icon_path))
            attr_button.setIconSize(QSize(55, 55))
            attr_button.setToolTip("No sfg")
            attr_button.setStyleSheet(""" QToolTip { background-color: white;
            color: black }""")
            attr_button.setParent(None)
            attr_button_scene = self.scene.addWidget(attr_button)
            attr_button_scene.moveBy(self.move_button_index * 100, 0)
            attr_button_scene.setFlag(attr_button_scene.ItemIsSelectable, True)
            self.move_button_index += 1
            operation_label = QGraphicsTextItem(attr_oper.type_name(), attr_button_scene)
            if not self.is_show_names:
                operation_label.setOpacity(0)
            operation_label.setTransformOriginPoint(operation_label.boundingRect().center())
            operation_label.moveBy(10, -20)
            attr_button.add_label(operation_label)
            self.operationDict[attr_button] = attr_button_scene
        except Exception as e:
            self.logger.error(f"Unexpected error occured while creating operation: {e}.")

    def _refresh_operations_list_from_namespace(self):
        self.logger.info("Refreshing operation list.")
        self.ui.core_operations_list.clear()
        self.ui.special_operations_list.clear()

        self.add_operations_from_namespace(c_oper, self.ui.core_operations_list)
        self.add_operations_from_namespace(s_oper, self.ui.special_operations_list)
        self.logger.info("Finished refreshing operation list.")

    def on_list_widget_item_clicked(self, item):
        self._create_operation(item)

    def keyPressEvent(self, event):
        if event.key() == Qt.Key_Delete:
            for pressed_op in self.pressed_operations:
                pressed_op.remove()
                self.move_button_index -= 1
            self.pressed_operations.clear()
        super().keyPressEvent(event)

    def connectButton(self, button):
        if len(self.pressed_ports) < 2:
            self.logger.warn("Can't connect less than two ports. Please select more.")
            return

        for i in range(len(self.pressed_ports) - 1):
            if isinstance(self.pressed_ports[i].port, OutputPort) and \
            isinstance(self.pressed_ports[i+1].port, InputPort):
                self.logger.info(f"Connecting: {self.pressed_ports[i].operation.operation.type_name()} -> {self.pressed_ports[i + 1].operation.operation.type_name()}")
                line = Arrow(self.pressed_ports[i], self.pressed_ports[i + 1], self)
                self.signalPortDict[line] = [self.pressed_ports[i], self.pressed_ports[i + 1]]

                self.scene.addItem(line)
                self.signalList.append(line)

        for port in self.pressed_ports:
            port.select_port()

        self.update()

    def paintEvent(self, event):
        for signal in self.signalPortDict.keys():
            signal.moveLine()

    def _select_all_operations(self):
        self.logger.info("Selecting all operations in the workspace.")
        self.pressed_operations.clear()
        for button in self.operationDict.keys():
            button._toggle_button(pressed=False)
            self.pressed_operations.append(button)

    def _select_operations(self):
        selected = [button.widget() for button in self.scene.selectedItems()]
        for button in selected:
            button._toggle_button(pressed=False)

        for button in self.pressed_operations:
            if button not in selected:
                button._toggle_button(pressed=True)

        self.pressed_operations = selected

    def _simulate_sfg(self):
        for sfg, properties in self.dialog.properties.items():
            self.logger.info(f"Simulating sfg with name: {sfg.name}.")
            simulation = Simulation(sfg, input_providers=properties["input_values"], save_results=properties["all_results"])
            l_result = simulation.run_for(properties["iteration_count"])

            if properties["all_results"]:
                print(f"{'=' * 10} {sfg.name} {'=' * 10}")
                pprint(simulation.results)
                print(f"{'=' * 10} /{sfg.name} {'=' * 10}")

            if properties["show_plot"]:
                self.logger.info(f"Opening plot for sfg with name: {sfg.name}.")
                self.logger.info("To save the plot press 'Ctrl+S' when the plot is focused.")
                self.plot = Plot(simulation, sfg, self)
                self.plot.show()

    def simulate_sfg(self):
        self.dialog = SimulateSFGWindow(self)

        for sfg in self.sfg_list:
            self.dialog.add_sfg_to_dialog(sfg)

        self.dialog.show()

        # Wait for input to dialog. Kinda buggy because of the separate window in the same thread.
        self.dialog.simulate.connect(self._simulate_sfg)

    def display_faq_page(self):
        self.faq_page = FaqWindow(self)
        self.faq_page.scroll_area.show()

    def display_about_page(self):
        self.about_page = AboutWindow(self)
        self.about_page.show()

    def display_keybinds_page(self):
        self.keybinds_page = KeybindsWindow(self)
        self.keybinds_page.show()


if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())