# info.py
#
# Copyright 2020-2023 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 gi.repository import GObject
from gi.repository import Gio
from gi.repository import Gdk
from gi.repository import Gtk

from ..config import FMT_DAY
from ..widgets import WebLinkActionRow, weblinkactionrowactivated
from ..utils import clean_markup


@Gtk.Template(resource_path="/net/kirgroup/confy/pages/info.ui")
class PageInfo(Gtk.Box):
    __gtype_name__ = "ConfyPageInfo"
    page_title = _("Event info")

    conf = None
    meta = None

    statuspage = Gtk.Template.Child()
    linkbox = Gtk.Template.Child()

    @GObject.Property(type=str, default="")
    def title(self):
        return clean_markup(self.meta.title) if self.meta else ""

    @GObject.Property(type=str, default="")
    def description(self):
        desc = self.meta.venue or ""
        if self.meta.venue and self.meta.city:
            desc += "\n"
        desc += self.meta.city or ""
        if desc != "":
            desc += "\n\n"
        desc += self.meta.start.strftime(FMT_DAY)
        if self.meta.start != self.meta.end:
            desc += "\n" + self.meta.end.strftime(FMT_DAY)
        return clean_markup(desc)

    def init(self, win, conf):
        self.conf = conf
        win.connect("conf-updated", self.update)
        return self

    def _set_logo(self, fetcher, logofile):
        self.statuspage.set_paintable(
            Gdk.Texture.new_from_file(
                Gio.File.new_for_path(logofile)
            )
        )

    def update(self, *_):
        self.meta = self.conf.get_meta()

        self.statuspage.set_icon_name('net.kirgroup.confy-symbolic')
        fetcher = self.conf.get_logo_file(cbk=self._set_logo)

        w = self.linkbox.get_last_child()
        while w:
            self.linkbox.remove(w)
            w = self.linkbox.get_last_child()

        links = self.conf.metadata.get("links", [])
        self.linkbox.set_visible(len(links) > 0)
        for link in links:
            row = WebLinkActionRow(link['title'], link['url'])
            self.linkbox.append(row)

        self.notify("title")
        self.notify("description")

    @Gtk.Template.Callback()
    def on_linkbox_row_activated(self, listbox, row):
        weblinkactionrowactivated(listbox, row)

