# Copyright 2021-2024 Teemu Ikonen
# SPDX-License-Identifier: GPL-3.0-only

import importlib.resources as resources

import gi
gi.require_version('Gtk', '4.0')
gi.require_version('Gdk', '4.0')
gi.require_version('Adw', '1')
from gi.repository import Adw, Gtk  # noqa: E402

respath = __name__.split(sep='.')[0]


@Gtk.Template(string=resources.read_text(respath, 'dataframe.ui'))
class DataFrame(Adw.Bin):

    __gtype_name__ = 'DataFrame'

    header = Gtk.Template.Child()
    grid = Gtk.Template.Child()

    def __init__(self, rowtitles=[], values=[], **kwargs):
        super().__init__(**kwargs)
        self.set_rowtitles(rowtitles)
        if values:
            self.set_values(values)

    def empty(self):
        child = self.grid.get_first_child()
        while child is not None:
            self.grid.remove(child)
            child = self.grid.get_next_sibling()
        self.rows = 0

    def set_rowtitles(self, rowtitles):
        self.empty()

        for num, title in enumerate(rowtitles):
            tlabel = Gtk.Label(label=title)
            tlabel.get_style_context().add_class("dim-label")
            tlabel.set_halign(Gtk.Align.END)
            vlabel = Gtk.Label(label="-")
            vlabel.set_halign(Gtk.Align.START)
            self.grid.attach(tlabel, 0, num, 1, 1)
            self.grid.attach(vlabel, 1, num, 1, 1)

        self.rows = len(rowtitles)

    def set_values(self, values):
        if len(values) != self.rows:
            raise ValueError("Number of values does not match rows")
        for num, val in enumerate(values):
            label = self.grid.get_child_at(1, num)
            label.set_text(val)
