import os

import gi

import stillCenter.constants as constants
from stillCenter.i18n import _

gi.require_version("Gtk", "4.0")
gi.require_version("Adw", "1")
from gi.repository import Gtk, Adw


@Gtk.Template(filename=os.path.join(constants.UI_DIR, "ErrorPage.ui"))
class ErrorPage(Adw.NavigationPage):
    __gtype_name__ = "ErrorPage"
    error_status: Adw.StatusPage = Gtk.Template.Child()
    retry_button: Gtk.Button = Gtk.Template.Child()
    stillCenter = None

    def __init__(self, stillCenter, error_title, error_description):
        super().__init__()
        self.stillCenter = stillCenter
        self._retry_callback = None
        self.retry_button.connect("clicked", self._on_retry_clicked)
        self.set_error(error_title, error_description)

    def set_error(self, error_title, error_description):
        description = (error_description or "").strip()
        if not description:
            description = _("An unexpected error occurred while loading this page.")

        self.error_status.set_title(error_title)
        self.error_status.set_description(description)

    def set_icon(self, icon_name):
        self.error_status.set_icon_name(icon_name)

    def set_retry(self, callback, label: str | None = None):
        if label is None:
            label = _("Refresh")
        self._retry_callback = callback
        self.retry_button.set_label(label)
        self.retry_button.set_visible(callback is not None)

    def _on_retry_clicked(self, _button):
        if self._retry_callback is not None:
            self._retry_callback(self)

    def push(self):
        self.stillCenter.main_view.push(self)

    def pop(self):
        self.stillCenter.main_view.pop()
