# ContextMenu.py -- Pamhyr
# Copyright (C) 2024-2025  INRAE
#
# 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.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.

# -*- coding: utf-8 -*-

from PyQt5.QtWidgets import (
    QMenu,
)


class AbstractMenu(object):
    def __init__(self, event=None, pos=None, items=[],
                 graph=None, trad=None, parent=None):
        super(AbstractMenu, self).__init__()

        self._menu = QMenu(parent)
        self._event = event
        self._pos = pos
        self._items = items

        self._graph = graph
        self._trad = trad
        self._parent = parent

    def map_to_global(self):
        return self._parent.mapToGlobal(self._event.pos())

    def _exec(self):
        return self._menu.exec_(self.map_to_global())

    def run(self):
        return


class DefaultMenu(AbstractMenu):
    def run(self):
        add_node = self._menu.addAction(self._trad["menu_add_scenario"])

        action = self._exec()
        if action == add_node:
            self._parent.new_scenario(self._pos)


class ScenarioMenu(AbstractMenu):
    def run(self):
        item = self._items[0]
        scenarios = item.graph._study.scenarios

        current_scenario = item.graph._study.status.scenario.id

        select = self._menu.addAction(self._trad["menu_select_scenario"])
        duplicate = None
        delete = None

        if item.scenario.id != 0:
            if scenarios.is_leaf(item.scenario):
                delete = self._menu.addAction(self._trad["menu_del_scenario"])

            if item.scenario.id == current_scenario:
                duplicate = self._menu.addAction(
                    self._trad["menu_dup_scenario"]
                )

        action = self._exec()
        if action is None:
            return
        elif action == select:
            self._parent.select_scenario(item)
        elif action == delete:
            self._parent.delete_scenario(item)
        elif action == duplicate:
            self._parent.duplicate_scenario(item)
