# Window.py -- Pamhyr
# Copyright (C) 2023-2026  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 View.Tools.PamhyrWindow import PamhyrDialog


class SelectReachWindow(PamhyrDialog):
    _pamhyr_ui = "SelectReach"
    _pamhyr_name = "Select reach"

    def __init__(self, study=None, config=None, trad=None, parent=None):

        super(SelectReachWindow, self).__init__(
            title=trad[self._pamhyr_name],
            study=study,
            config=config,
            options=[],
            parent=parent
        )

        self.setup_combobox()
        self.select_current_reach()

    def setup_combobox(self):
        reaches = list(self._study.river.enable_edges())
        reaches_name = [r.name for r in reaches]

        self.combobox_add_items("comboBox", reaches_name)

    def select_current_reach(self):
        if self._study.river.has_current_reach():
            reach = self._study.river.current_reach()
            self.set_combobox_text(
                "comboBox",
                reach.name
            )

    def accept(self):
        reach_name = self.get_combobox_text("comboBox")

        reach = next(
            filter(
                lambda s: s.name == reach_name,
                self._study.river.enable_edges()
            )
        )

        self.reach = reach

        super().accept()

    def reject(self):
        self.close()
