# preferences.py
#
# Copyright 2020-2022 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 Gio
from gi.repository import Gtk
from gi.repository import Adw

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 PreferencesWindow(Adw.PreferencesWindow):
    def __init__(self, **kwargs):
        opts = dict(
            default_height=290,
            default_width=640,
            search_enabled=False,
        )
        opts.update(kwargs)
        super().__init__(**opts)

        page = Adw.PreferencesPage()

        group = Adw.PreferencesGroup()

        listcache = Adw.ComboRow(
            title=_("Events list cache duration"),
            subtitle=_("Try to update list cache when it's older than this."))
        listcache.set_model(CacheDuration.as_model())
        Settings.instance().bind('list-cache', listcache, 'selected', Gio.SettingsBindFlags.DEFAULT)

        eventcache = Adw.ComboRow(
            title=_("Events info cache duration"),
            subtitle=_("Try to update event cache when it's older than this."))
        eventcache.set_model(CacheDuration.as_model())
        Settings.instance().bind('event-cache', eventcache, 'selected', Gio.SettingsBindFlags.DEFAULT)

        group.add(listcache)
        group.add(eventcache)
        page.add(group)

        group = Adw.PreferencesGroup()
        button = Gtk.Button(label=_("Clear"),
                            valign=Gtk.Align.CENTER, halign=Gtk.Align.END)
        button.get_style_context().add_class("list-button")
        row = Adw.ActionRow(
            title=_("Cached data"))
        self._update_space_label(row)
        row.add_suffix(button)
        row.set_activatable_widget(button)
        button.connect("clicked", self._delete_cached_files, row)
        group.add(row)
        page.add(group)

        self.add(page)

    def _delete_cached_files(self, btn, row):
        local.clear_cache()
        self._update_space_label(row)

    def _update_space_label(self, row):
        cache_size = local.get_cache_size()
        occupied_space = format_size(cache_size)
        row.set_subtitle(_("Confy has {} of cached data").format(occupied_space))
