# -*- 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 gettext

# External libraries
from tblock.const import Profile, Components

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

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


class IntroActivity:
    """
    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("IntroActivity")
        self.window.set_application(self._application)

        self._profile = None
        self._additional_filter_lists = []

        self.threaded_activity = JobController(
            application=self._application,
            status_label=self._application.builder.get_object(
                "IntroActivityStatusLabel"
            ),
            status_bar=self._application.builder.get_object("IntroActivityStatusBar"),
            finish_button=self._application.builder.get_object(
                "IntroActivityFinishButton"
            ),
        )

    def start(self) -> None:
        """
        Start the activity
        """
        self.go_to_page(0)
        self.window.show_all()
        # Set the default profile to BALANCED
        self._application.builder.get_object("IntroActivityProfileBalanced").set_active(
            True
        )
        self.select_profile(Profile.BALANCED)
        self._application.builder.get_object(
            "IntroActivitySettingsSecurity"
        ).set_active(False)
        self._application.builder.get_object("IntroActivitySettingsHate").set_active(
            False
        )
        self._application.builder.get_object("IntroActivitySettingsPorn").set_active(
            False
        )
        self._application.builder.get_object(
            "IntroActivitySettingsFakeNews"
        ).set_active(False)
        self._application.builder.get_object("IntroActivitySettingsDrugs").set_active(
            False
        )
        self._application.builder.get_object("IntroActivitySettingsPiracy").set_active(
            False
        )
        self._application.builder.get_object(
            "IntroActivitySettingsGambling"
        ).set_active(False)

    def go_to_page(self, number: int) -> None:
        """
        Go to a selected page of the activity

        :param number: The index of the page to go to
        """
        self._application.builder.get_object(
            "IntroActivityStack"
        ).set_visible_child_name(f"IntroActivityPage{number}")

    def select_profile(self, profile: list) -> None:
        """
        Select the profile to use for initial setup

        :param profile: A value of the Profile enum
        """
        self._profile = profile
        desc = ""
        if self._profile == Profile.NONE:
            desc = _("A profile that will let you configure everything yourself.")
        elif self._profile == Profile.LIGHT:
            desc = _(
                "This profile is light, but some ads and trackers won't be blocked."
            )
        elif self._profile == Profile.BALANCED:
            desc = _(
                "This efficient profile is the perfect solution for regular users."
            )
        elif self._profile == Profile.AGGRESSIVE:
            desc = _("A powerful profile that may however break some web pages.")
        self._application.builder.get_object("IntroActivityProfileDesc").set_text(desc)

    def toggle_settings(self, component: list) -> None:
        """
        Add additional filter lists to subscribe to

        :param component: The set of filter lists to use
        """
        _builder_id = None
        if component == Components.SECURITY:
            _builder_id = "IntroActivitySettingsSecurity"
        elif component == Components.PORNOGRAPHY:
            _builder_id = "IntroActivitySettingsPorn"
        elif component == Components.FAKE_NEWS:
            _builder_id = "IntroActivitySettingsFakeNews"
        elif component == Components.DRUGS:
            _builder_id = "IntroActivitySettingsDrugs"
        elif component == Components.PIRACY:
            _builder_id = "IntroActivitySettingsPiracy"
        elif component == Components.GAMBLING:
            _builder_id = "IntroActivitySettingsGambling"
        elif component == Components.HATE:
            _builder_id = "IntroActivitySettingsHate"

        if _builder_id is not None:
            if self._application.builder.get_object(_builder_id).get_active():
                self._additional_filter_lists += component
            else:
                self._additional_filter_lists = list(
                    set(self._additional_filter_lists) - set(component)
                )

    def run_thread(self) -> None:
        """
        Run the setup operation
        """
        _auth_err_code = pk_dummy_authenticate()
        if _auth_err_code == ExitStatusCode.NO_ERROR:
            self.go_to_page(6)
            self.threaded_activity.manage_filter_lists(
                filter_lists=self._profile + self._additional_filter_lists,
                sync=True,
                build_hosts=True,
                unsubscribe=False,
            )
        else:
            self._application.error_window.handle_error(_auth_err_code)

    def quit(self) -> None:
        """
        Quit the intro activity
        """
        if self.threaded_activity.running:
            self.threaded_activity.kill()
        if get_setting(GUISettings.SETUP_COMPLETED.value):
            self.window.hide()
        else:
            self._application.quit()
