# -*- coding: utf-8 -*-
#  _____  ____   _               _
# |_   _|| __ ) | |  ___    ___ | | __
#   | |  |  _ \ | | / _ \  / __|| |/ /
#   | |  | |_) || || (_) || (__ |   <
#   |_|  |____/ |_| \___/  \___||_|\_\
#
# Copyright (C) 2021-2025 Camelia Lavender <camelia@tblock.me>

# 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 <https://www.gnu.org/licenses/>.

# Standard libraries
import os.path
import gettext
from typing import AnyStr

# External libraries
import tblock.utils
import tblock.exceptions
import gi

# Local libraries
from .config import get_setting, GUISettings
from .const import ExitStatusCode
from ._polkit import pk_subprocess_run, pk_dummy_authenticate

gi.require_version("Gtk", "3.0")
# pylint: disable=wrong-import-position,wrong-import-order
from gi.repository import GLib

gettext.textdomain("tblock-gui")
_ = gettext.gettext


class SettingsActivity:
    """
    Class that interacts with the activity of the same name from the glade UI
    """

    def __init__(self, application):
        """
        Initiate the activity

        :param application: An object of type Gtk.Application
        """
        self._application = application
        self.window = self._application.builder.get_object("SettingsActivity")
        self.window.set_application(self._application)

    def start(self) -> None:
        """
        Start the activity
        """
        self.refresh()
        self.window.show_all()

    def refresh(self) -> None:
        """
        Refresh the activity
        """
        daemon_label = self._application.builder.get_object(
            "SettingsActivityStatusLabelDaemon"
        )
        db_label = self._application.builder.get_object(
            "SettingsActivityStatusLabelDatabase"
        )
        storage_label = self._application.builder.get_object(
            "SettingsActivityStatusLabelStorage"
        )
        if os.path.isfile(tblock.Path.DAEMON_PID):
            daemon_label.set_text(_("enabled"))
        else:
            daemon_label.set_text(_("disabled"))
        try:
            size = tblock.utils.get_readable_size(tblock.utils.get_db_size())
        except FileNotFoundError:
            db_label.set_text(_("no database"))
            size = 0
        else:
            if tblock.utils.db_is_locked():
                db_label.set_text(_("locked"))
            else:
                db_label.set_text(_("unlocked"))
        storage_label.set_text(size)

        logging_enabled = get_setting(GUISettings.LOGGING_ENABLED.value)
        self._application.builder.get_object(
            GUISettings.LOGGING_ENABLED.value
        ).set_active(logging_enabled)

        check_update = get_setting(GUISettings.UPDATE_STARTUP_CHECK.value)
        self._application.builder.get_object(
            GUISettings.UPDATE_STARTUP_CHECK.value
        ).set_active(check_update)

        update_beta = get_setting(GUISettings.UPDATE_BETA.value)
        self._application.builder.get_object(GUISettings.UPDATE_BETA.value).set_active(
            update_beta
        )

    def setting_switch(self, setting_name: AnyStr) -> None:
        """
        Change a setting
        """
        _auth_err_code = pk_dummy_authenticate()
        if _auth_err_code == ExitStatusCode.NO_ERROR:
            if (
                pk_subprocess_run(
                    [
                        "setting",
                        setting_name,
                        str(
                            int(
                                not self._application.builder.get_object(
                                    setting_name
                                ).get_active()
                            )
                        ),
                    ]
                )
                != ExitStatusCode.NO_ERROR
            ):
                self._application.error_window.raise_error(
                    _("Failed to change GUI settings.")
                )
        else:
            self._application.error_window.handle_error(_auth_err_code)
        GLib.timeout_add(200, self.refresh)

    def run_unlock(self) -> None:
        """
        Run the operation to unlock the database
        """
        if self._application.warning_window.prompt_database_unlock():
            if not os.path.isfile(tblock.Path.DB_LOCK):
                self._application.error_window.raise_db_unlocked_error()
            else:
                _auth_err_code = pk_dummy_authenticate()
                if _auth_err_code == ExitStatusCode.NO_ERROR:
                    if pk_subprocess_run(["unlock"]) != ExitStatusCode.NO_ERROR:
                        self._application.error_window.raise_error(
                            _("Failed to unlock database.")
                        )
                else:
                    self._application.error_window.handle_error(_auth_err_code)
                self.refresh()

    def quit(self) -> None:
        """
        Quit the activity
        """
        self.window.hide()
