from pyqtgraph.parametertree.parameterTypes import ActionParameter, ActionParameterItem
from pyqtgraph.parametertree.parameterTypes.action import (
    ParameterControlledButton,
    ParameterItem,
)
from qgis.PyQt import QtCore, QtGui, QtWidgets
from qgis.PyQt.QtCore import QSize, Qt, pyqtSignal
from qgis.PyQt.QtGui import QIcon
from qgis.PyQt.QtWidgets import QAction, QMenu


class SaveLoadActionParameterItem(ActionParameterItem):
    """
    Subclass of ActionParameterItem to add a menu with two options.
    """

    db_action = QAction("Database")
    file_action = QAction("JSON file")

    def __init__(self, param, depth):
        ParameterItem.__init__(self, param, depth)
        self.layoutWidget = QtWidgets.QWidget()
        self.layout = QtWidgets.QHBoxLayout()
        self.layout.setContentsMargins(0, 0, 0, 0)
        self.layoutWidget.setLayout(self.layout)
        self.button = ParameterControlledButton(param, self.layoutWidget)
        self.menu = QMenu(self.button)
        self.menu.addAction(self.db_action)
        self.menu.addAction(self.file_action)
        self.button.setMenu(self.menu)

        if "tooltip" in param.opts.keys():
            self.button.setToolTip(param.opts["tooltip"])

        self.layout.addWidget(self.button, alignment=Qt.AlignLeft)
        self.titleChanged()

    @classmethod
    def get_distinct_actions_cls(cls):
        """
        QActions should be different instances for signal connections.
        """

        class Newcls(cls):
            db_action = QAction(
                QIcon(":images/themes/default/dbmanager.svg"), "Database"
            )
            file_action = QAction(
                QIcon(":images/themes/default/mIconFieldJson.svg"), "JSON file"
            )

        return Newcls


class SaveLoadActionParameter(ActionParameter):

    # signals are emitted from this class
    sig_db_action = pyqtSignal()
    sig_file_action = pyqtSignal()

    def __init__(self, **opts):
        self.itemClass = SaveLoadActionParameterItem.get_distinct_actions_cls()
        super().__init__(**opts)

        # connect parameteritem signals to emit from this class
        self.itemClass.db_action.triggered.connect(self.sig_db_action.emit)
        self.itemClass.file_action.triggered.connect(self.sig_file_action.emit)
