# preferences.py
#
# Copyright 2020-2025 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 gettext import gettext as _

from gi.repository import GObject
from gi.repository import Gio
from gi.repository import Gtk
from gi.repository import Adw

from .config import APP_NAME  # type:ignore # config is generated at compile time
from .settings import Settings, CacheDuration
from . import local


def format_size(num):
    for unit in ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB']:
        if abs(num) < 1024.0:
            return "%3.1f%s" % (num, unit)
        num /= 1024.0
    return "%.1f%s" % (num, 'Yi')


class SettingsCacheDurationRow(Adw.ComboRow):
    __gtype_name__ = "ConfySettingsCacheDurationRow"
    setting_key: str = GObject.Property(type=str, default="")

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.set_model(CacheDuration.as_model())
        self.connect("notify::setting-key", self._setup)

    def _setup(self, *args):
        Settings.instance().bind(self.setting_key, self, 'selected', Gio.SettingsBindFlags.DEFAULT)


@Gtk.Template(resource_path="/net/kirgroup/confy/preferences.ui")
class PreferencesWindow(Adw.PreferencesWindow):
    __gtype_name__ = "ConfyPreferencesWindow"

    @GObject.Property(type=str, default="", flags=GObject.ParamFlags.READABLE)
    def cache_space_label(self):
        cache_size = local.get_cache_size()
        occupied_space = format_size(cache_size)
        return _("Confy has {} of cached data").format(occupied_space)

    @Gtk.Template.Callback()
    def _delete_cached_files(self, btn, *_):
        local.clear_cache()
        self.notify("cache-space-label")

    @Gtk.Template.Callback()
    def _delete_recents(self, btn, *_):
        recentmanager = Gtk.RecentManager.get_default()
        for item in recentmanager.get_items():
            if item.has_application(APP_NAME):
                recentmanager.remove_item(item.get_uri())

