from gettext import gettext as _
import gi

gi.require_version("GtkSource", "5")
from gi.repository import Adw, Gio, GObject, Gtk, GtkSource

import iotas.config_manager
from iotas.ui_utils import ComboRowHelper


@Gtk.Template(resource_path="/org/gnome/gitlab/cheywood/Iotas/ui/preferences_window.ui")
class PreferencesWindow(Adw.PreferencesWindow):
    __gtype_name__ = "PreferencesWindow"

    _editor_theme_row = Gtk.Template.Child()
    _index_category_style_row = Gtk.Template.Child()
    _disconnect_sync = Gtk.Template.Child()
    _debug_page = Gtk.Template.Child()

    def __init__(self):
        super().__init__()
        self.__app = Gio.Application.get_default()
        self.set_transient_for(self.__app.get_active_window())
        self.__build_actions()

    def __build_actions(self) -> None:
        action_group = Gio.SimpleActionGroup.new()

        key = iotas.config_manager.USE_MONOSPACE_FONT
        monospace_font_action = iotas.config_manager.settings.create_action(key)
        action_group.add_action(monospace_font_action)

        key = iotas.config_manager.SPELLING_ENABLED
        spelling_action = iotas.config_manager.settings.create_action(key)
        action_group.add_action(spelling_action)

        key = iotas.config_manager.MARKDOWN_SYNTAX_HIGHLIGHTING
        syntax_action = iotas.config_manager.settings.create_action(key)
        action_group.add_action(syntax_action)

        key = iotas.config_manager.MARKDOWN_RENDER
        render_action = iotas.config_manager.settings.create_action(key)
        action_group.add_action(render_action)

        self.insert_action_group("settings", action_group)

        scheme_manager = GtkSource.StyleSchemeManager.get_default()
        options = []
        scheme_ids = scheme_manager.get_scheme_ids()

        # Preference and order internal schemes
        def add_preferenced_scheme(scheme_id):
            if scheme_id not in scheme_ids:
                return
            scheme = scheme_manager.get_scheme(scheme_id)
            options.append((scheme.get_name(), scheme_id))

        preferenced_schemes = ("iotas-mono", "iotas-alpha-muted", "iotas-alpha-bold")
        for scheme_id in preferenced_schemes:
            add_preferenced_scheme(scheme_id)

        # Add other schemes (eg. in user data)
        for scheme_id in scheme_ids:
            if scheme_id in preferenced_schemes:
                continue
            # Only Iotas-specific schemes, prefixed with "iotas-", are supported
            if scheme_id.startswith("iotas-") and not scheme_id.endswith("-dark"):
                scheme = scheme_manager.get_scheme(scheme_id)
                options.append((scheme.get_name(), scheme_id))

        helper = ComboRowHelper(
            self._editor_theme_row,
            options,
            iotas.config_manager.get_editor_theme(),
        )
        helper.connect("changed", self.__on_editor_theme_changed)

        options = (
            # Translators: Description, a visual style (for category labels in index)
            (_("Monochrome"), "monochrome"),
            # Translators: Description, a visual style (for category labels in index)
            (_("Muted"), "muted"),
            # Translators: Description, a visual style (for category labels in index)
            (_("Blue"), "blue"),
            # Translators: Description, a visual style (for category labels in index)
            (_("Orange"), "orange"),
            # Translators: Description, a visual style (for category labels in index)
            (_("Red"), "red"),
            # Translators: Description, a visual style (for category labels in index)
            (_("None"), "none"),
        )
        helper = ComboRowHelper(
            self._index_category_style_row,
            options,
            iotas.config_manager.get_index_category_style(),
        )
        helper.connect("changed", self.__on_index_category_style_changed)

        self._disconnect_sync.set_visible(iotas.config_manager.nextcloud_sync_configured())
        if not (self.__app.debug_session or self.__app.development_mode):
            self.remove(self._debug_page)

    @Gtk.Template.Callback()
    def _reset_database(self, _button: Gtk.Button) -> None:
        self.__app.reset_database()

    @Gtk.Template.Callback()
    def _disconnect_nextcloud(self, _button: Gtk.Button) -> None:
        self.__app.disconnect_nextcloud()

    @Gtk.Template.Callback()
    def _reset_prune_threshold(self, _button: Gtk.Button) -> None:
        self.__app.reset_sync_marker()

    def __on_editor_theme_changed(self, _obj: GObject.Object, value: str) -> None:
        iotas.config_manager.set_editor_theme(value)

    def __on_index_category_style_changed(self, _obj: GObject.Object, value: str) -> None:
        iotas.config_manager.set_index_category_style(value)
