# widgets/navbar.py
#
# Copyright 2020-2024 Fabio Comuni, et al.
#
# 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 <http://www.gnu.org/licenses/>.
from dataclasses import dataclass

from gi.repository import GObject
from gi.repository import Gtk


class NavbarListItem(Gtk.ListBoxRow):
    __gtype_name__ = "ConfyNavbarListItem"

    def __init__(self, item, **kwargs):
        super().__init__(**kwargs)
        self.item = item

        box = Gtk.Box(spacing=8)
        icon = Gtk.Image(icon_name=item.icon)
        label = Gtk.Label(halign=Gtk.Align.START, label=item.label)
        box.append(icon)
        box.append(label)
        self.set_child(box)


@dataclass
class NavbarItem:
    name: str = ""
    icon: str = ""
    label: str = ""
    group: int = 0


class Navbar(Gtk.ListBox):
    __gtype_name__ = "ConfyNavbar"

    model: list[NavbarItem] = []
    _current_item = None  # type: ignore

    @GObject.Signal
    def page_changed(self):
        ...

    def __init__(self, **kwargs):
        super().__init__(hexpand=True)
        self.add_css_class("navigation-sidebar")
        self.connect("row-activated", self._on_nav)

    def update(self):
        self.remove_all()
        found = False
        for idx, item in enumerate(self.model):
            widget = NavbarListItem(item)
            if self._current_item and item == self._current_item:
                found = True
                self.select_row(widget)
            self.append(widget)

        if not found:
            self._current_item = self.model[0]
            self.select_row(self.get_row_at_index(0))
            self.emit("page-changed")

    def _on_nav(self, sender, row):
        self._current_item = row.item
        self.emit("page-changed")

    def get_current_item(self) -> NavbarItem:
        return self._current_item  # type: ignore

    def set_item_cond(self, item: NavbarItem, cond: bool):
        """
            if cond is true and item not in model, item is appended
            if cond is false and item is in model, item is removed
        """
        if cond:
            if item not in self.model:
                self.model.append(item)
                self.update()
        else:
            if item in self.model:
                self.model.remove(item)
                self.update()
