from qgis.PyQt.QtCore import QCoreApplication, Qt
from qgis.PyQt.QtGui import QIcon
######################################################################
#             / ____|  ____|  __ \| |  | |  ____|  ____|             #
#            | |    | |__  | |__) | |__| | |__  | |__                #
#            | |    |  __| |  ___/|  __  |  __| |  __|               #
#            | |____| |____| |    | |  | | |____| |____              #
#             \_____|______|_|    |_|  |_|______|______|             #
######################################################################
#
# CEPHEE
# Copyright (C) 2024 Toulouse INP
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU General Public License for more details :
# <http://www.gnu.org/licenses/>.
#
######################################################################

from qgis.PyQt.QtWidgets import QAction, QToolBar, QMenu, QDockWidget
import os
from .gui.MainWindow import MainWindow
from .gui.DataWidget import DataWidget
from .gui.CrossSectionWidget import CrossSectionWidget
from .gui.HydraulicWidget import HydraulicWidget
from .gui.BathymetricWidget import BathymetricWidget
from .gui.PlotWidget import PlotWidget
from .core.Parameters import Parameters
from .core.ModelCatchment import ModelCatchment


class qCEPHEE:

    """QGIS Plugin Implementation."""
    def __init__(self, iface):
        """Constructor.

        :param iface: An interface instance that will be passed to this class
            which provides the hook by which you can manipulate the QGIS
            application at run time.
        :type iface: QgsInterface
        """

        # Save reference to the QGIS interface
        self.iface = iface
        self.main_widget = None
        self.plot_widget = None
        self.menu = None
        self.main_action = None
        self.plot_action = None
        self.docks = []

        toolbars = self.iface.mainWindow().findChildren(QToolBar)
        test = True
        for toolbar1 in toolbars:
            if toolbar1.windowTitle() == "qCEPHEE":
                self.toolbar = toolbar1
                test = False
                break
        if test:
            self.toolbar = self.iface.addToolBar("qCEPHEE")
            self.toolbar.setObjectName("qCEPHEE")

        self.pluginIsActive = False
        self.dockwidget = None

        self.param = Parameters()
        self.BV = ModelCatchment(True)

    def tr(self, message):
        """Get the translation for a string using Qt translation API.
        We implement this ourselves since we do not inherit QObject.
        :param message: String for translation.
        :type message: str, QString
        :returns: Translated version of message.
        :rtype: QString
        """
        return QCoreApplication.translate("qCEPHEE", message)

    def initGui(self):
        """Create the menu entries and toolbar icons inside the QGIS GUI."""

        self.main_widget = MainWindow(self.iface, self.BV, self.param, self.iface.mainWindow())

        plg_dir = os.path.dirname(__file__)
        main_icon = QIcon(os.path.join(plg_dir, "img", "logo.png"))
        plot_icon = QIcon(os.path.join(plg_dir, "img", "plot_icon.png"))
        self.main_action = QAction(
            main_icon, "qCEPHEE", self.iface.mainWindow()
        )

        self.menu = QMenu()
        self.main_action.setMenu(self.menu)
        self.main_action.triggered.connect(self.open_main_widget)

        actions = [
            {
                "name": "Data Widget",
                "widget": DataWidget(self.iface, self.BV, self.param, self.iface.mainWindow()),
                "icon": main_icon
            },
            {
                "name": "Cross Section Widget",
                "widget": CrossSectionWidget(self.iface, self.BV, self.param, self.iface.mainWindow()),
                "icon": main_icon
            },
            {
                "name": "Hydraulic Widget",
                "widget": HydraulicWidget(self.iface, self.BV, self.param, self.iface.mainWindow()),
                "icon": main_icon
            },
            {
                "name": "Bathymetric Widget",
                "widget": BathymetricWidget(self.iface, self.BV, self.param, self.iface.mainWindow()),
                "icon": main_icon
            }
        ]

        for action in actions:
            self.add_action(action["name"], action["widget"], action["icon"])

        self.toolbar.addAction(self.main_action)

        # Add plot action
        self.plot_widget = PlotWidget(self.iface, self.BV, self.param)
        self.plot_action = QAction(
            plot_icon, "Profile plot", self.iface.mainWindow()
        )
        self.toolbar.addAction(self.plot_action)
        self.plot_action.triggered.connect(self.open_plot_widget)

    def open_main_widget(self):
        self.main_widget.show()

    def open_plot_widget(self):
        self.plot_widget.update_reach_list()
        self.plot_widget.show()

    def add_action(self, name, widget, icon):
        dock = QDockWidget(name, self.iface.mainWindow())
        dock.setWindowIcon(icon)
        dock.setWidget(widget)
        self.iface.addDockWidget(Qt.RightDockWidgetArea, dock)
        dock.close()
        self.docks.append(dock)
        dock.toggleViewAction().setIcon(widget.windowIcon())
        self.menu.addAction(dock.toggleViewAction())

    def onCloseWidget(self):
        """Cleanup necessary items here when plugin dockwidget is closed"""
        # disconnects
        self.dockwidget.closingWidget.disconnect(self.onCloseWidget)
        self.pluginIsActive = False


    def unload(self):
        if self.main_action:
            self.iface.removeToolBarIcon(self.main_action)
            del self.main_action
        if self.plot_action:
            self.iface.removeToolBarIcon(self.plot_action)
            del self.plot_action
        if self.main_widget:
            self.main_widget.deleteLater()
            self.main_widget = None
        if self.menu:
            del self.menu
        for _dock in self.docks:
            self.iface.removeDockWidget(_dock)
            _dock.deleteLater()
        self.docks.clear()


    def run(self):
        if not self.pluginIsActive:
            self.pluginIsActive = True
            # Create the dockwidget
            if self.dockwidget is None:
                self.dockwidget = MainWindow(self.iface, self.BV, self.param)
            self.dockwidget.closingWidget.connect(self.onCloseWidget)
            self.iface.addDockWidget(Qt.DockWidgetArea.RightDockWidgetArea, self.dockwidget)
            self.dockwidget.show()
        else:
            self.iface.removeDockWidget(self.dockwidget)
            self.dockwidget.closingWidget.emit()