# SPDX-FileCopyrightText: 2022 Chris Heywood
#
# SPDX-License-Identifier: GPL-3.0-or-later

from gi.repository import GObject, Gtk

from iotas.category import Category


class CategoryTreeViewListStore(Gtk.ListStore):

    def __init__(self) -> None:
        super().__init__(GObject.TYPE_STRING, Category)

    def populate(self, categories: list[Category]) -> None:
        """Populate store with categories.

        :param list[Category] categories: Categories to populate
        """
        for category in categories:
            iter = self.append()
            self.set_value(iter, 0, category.display_name)
            self.set_value(iter, 1, category)

    def add(self, category: Category) -> None:
        """Add category to store.

        :param Category category: Category to remove
        """
        iter = self.get_iter_first()
        if iter is None:
            new_iter = self.append()
        else:
            while iter is not None:
                if self.get_value(iter, 1).name.lower() > category.name.lower():
                    break
                iter = self.iter_next(iter)
            new_iter = self.insert_before(iter)
        self.set_value(new_iter, 0, category.display_name)
        self.set_value(new_iter, 1, category)

    def delete(self, category: Category) -> None:
        """Remove category from store.

        :param Category category: Category to remove
        """
        iter = self.get_iter_first()
        while iter is not None:
            if self.get_value(iter, 1).name == category.name:
                self.remove(iter)
                break
            iter = self.iter_next(iter)
