#!/usr/bin/python3
"""App configuration for Wire-Py"""

import gettext
import locale
from pathlib import Path
import subprocess
from typing import Dict, Any


class AppConfig:
    """Central configuration class for Wire-Py application"""

    # Localization
    APP_NAME: str = "wirepy"
    LOCALE_DIR: Path = Path("/usr/share/locale/")

    # Base paths
    BASE_DIR: Path = Path.home()
    CONFIG_DIR: Path = BASE_DIR / ".config/wire_py"
    TEMP_DIR: Path = Path("/tmp/tlecdcwg")
    USER_FILE: Path = Path("/tmp/.log_user")
    PUBLICKEY: Path = CONFIG_DIR / "pbwgk.pem"

    # Configuration files
    SETTINGS_FILE: Path = CONFIG_DIR / "settings"
    KEYS_FILE: Path = CONFIG_DIR / "keys"
    SYSTEMD_USER_FOLDER: Path = Path.home() / ".config/systemd/user"
    AUTOSTART_SERVICE: Path = Path.home() / ".config/systemd/user/wg_start.service"
    DEFAULT_SETTINGS: Dict[str, str] = {
        "# Configuration": "on",
        "# Theme": "dark",
        "# Tooltips": True,
        "# Autostart": "off",
    }

    # Updates
    # 1 = 1. Year, 09 = Month of the Year, 2924 = Day and Year of the Year
    VERSION: str = "v. 2.04.1725"
    UPDATE_URL: str = "https://git.ilunix.de/api/v1/repos/punix/Wire-Py/releases"
    DOWNLOAD_URL: str = "https://git.ilunix.de/punix/Wire-Py/archive"

    # UI configuration
    UI_CONFIG: Dict[str, Any] = {
        "window_title": "Wire-Py",
        "window_size": (600, 383),
        "font_family": "Ubuntu",
        "font_size": 11,
        "resizable_window": (False, False),
    }

    # System-dependent paths
    SYSTEM_PATHS: Dict[str, str] = {
        "ssl_decrypt": "/usr/local/bin/ssl_decrypt.py",
        "ssl_encrypt": "/usr/local/bin/ssl_encrypt.py",
        "tcl_path": "/usr/share/TK-Themes",
        "pkey_path": "/usr/local/etc/ssl/pwgk.pem",
    }

    # Images and icons paths
    IMAGE_PATHS: Dict[str, str] = {
        "icon_vpn": "/usr/share/icons/lx-icons/48/wg_vpn.png",
        "icon_msg": "/usr/share/icons/lx-icons/48/wg_msg.png",
        "icon_import": "/usr/share/icons/lx-icons/48/wg_import.png",
        "icon_export": "/usr/share/icons/lx-icons/48/wg_export.png",
        "icon_trash": "/usr/share/icons/lx-icons/48/wg_trash.png",
        "icon_start": "/usr/share/icons/lx-icons/48/wg_vpn-start.png",
        "icon_stop": "/usr/share/icons/lx-icons/48/wg_vpn-stop.png",
        "icon_info": "/usr/share/icons/lx-icons/64/info.png",
        "icon_error": "/usr/share/icons/lx-icons/64/error.png",
    }

    @staticmethod
    def setup_translations() -> gettext.gettext:
        """
        Initialize translations and set the translation function
        Special method for translating strings in this file

        Returns:
            The gettext translation function
        """
        locale.bindtextdomain(AppConfig.APP_NAME, AppConfig.LOCALE_DIR)
        gettext.bindtextdomain(AppConfig.APP_NAME, AppConfig.LOCALE_DIR)
        gettext.textdomain(AppConfig.APP_NAME)
        return gettext.gettext

    @classmethod
    def ensure_directories(cls) -> None:
        """Ensures that all required directories exist"""
        if not cls.CONFIG_DIR.exists():
            cls.CONFIG_DIR.mkdir(parents=True, exist_ok=True)
        cls.TEMP_DIR.mkdir(parents=True, exist_ok=True)

    @classmethod
    def create_default_settings(cls) -> None:
        """Creates default settings if they don't exist"""
        if not cls.SETTINGS_FILE.exists():
            content = "\n".join(
                f"[{k.upper()}]\n{v}" for k, v in cls.DEFAULT_SETTINGS.items()
            )
            cls.SETTINGS_FILE.write_text(content)

    @classmethod
    def get_autostart_content(cls) -> str:
        """Returns the content for the autostart service file"""
        SYSTEMD_FILE: list[str] = [
            "[Unit]",
            "Description=Automatic Tunnel Start",
            "After=network-online.target",
            "",
            "[Service]",
            "Type=oneshot",
            "ExecStartPre=/bin/sleep 5",
            "ExecStart=/usr/local/bin/start_wg.py",
            "",
            "[Install]",
            "WantedBy=default.target",
        ]
        if not cls.SYSTEMD_USER_FOLDER.exists():
            cls.SYSTEMD_USER_FOLDER.mkdir(parents=True, exist_ok=True)

        for line in SYSTEMD_FILE:
            cls.AUTOSTART_SERVICE.write_text(line)

        process = subprocess.run(
            ["systemctl", "--user", "enable", "wg_start.service"],
            stdout=subprocess.PIPE,
            text=True,
            check=True,
        )
        print(process.stdout)
        if process.returncode == 0:
            print("File for autostart created successfully")
            print(process.stdout)
        else:
            print(f"Error with the following code... {process.returncode}")


# here is inizialize the class for translate strrings
_ = AppConfig.setup_translations()


class Msg:
    """
    A utility class that provides centralized access to translated message strings.

    This class contains a dictionary of message strings used throughout the Wire-Py application.
    All strings are prepared for translation using gettext. The short key names make the code
    more concise while maintaining readability.

    Attributes:
        STR (dict): A dictionary mapping short keys to translated message strings.
                   Keys are abbreviated for brevity but remain descriptive.

    Usage:
        Import this class and access messages using the dictionary:
        `Msg.STR["sel_tl"]` returns the translated "Select tunnel" message.

    Note:
        Ensure that gettext translation is properly initialized before
        accessing these strings to ensure correct localization.
    """

    STR: Dict[str, str] = {
        # Strings for messages
        "sel_tl": _("Select tunnel"),
        "ren_err": _("Renaming not possible"),
        "exp_succ": _("Export successful"),
        "exp_in_home": _("Your zip file is in home directory"),
        "imp_err": _("Import Error"),
        "exp_err": _("Export Error"),
        "exp_try": _("Export failed! Please try again"),
        "tl_first": _("Please first import tunnel"),
        "sel_list": _("Please select a tunnel from the list"),
        "sign_len": _("The new name may contain only 12 characters"),
        "zero_signs": _("At least one character must be entered"),
        "false signs": _(
            "No valid sign. These must not be used.\nBlank, Slash, Backslash and { }\n"
        ),
        "is_in_use": _("The tunnel is already in use"),
        "no_valid_file": _(
            "Oh... no valid Wireguard File!\nPlease select a valid Wireguard File"
        ),
        "tl_exist": _("Tunnel already available!\nPlease use another file for import"),
    }
    TTIP: Dict[str, str] = {
        # Strings for Tooltips
        "settings": _("Click for Settings"),
        "import_tl": _("Click to import a Wireguard Tunnel"),
        "start_tl": _("Click to start selected Wireguard Tunnel"),
        "empty_list": _("No tunnels to start in the list"),
        "stop_tl": _("Click to stop selected Wireguard Tunnel"),
        "del_tl": _("Click to delete selected Wireguard Tunnel"),
        "rename_tl": _(
            "To rename a tunnel, you need to\nselect a tunnel from the list"
        ),
        "export_tl": _("         Click to export all\nWireguard Tunnel to Zipfile"),
        "trash_tl": _("Click to delete a Wireguard Tunnel\nSelect from the list!"),
        "autostart": _("To use the autostart, enable this Checkbox"),
        "autostart_info": _(
            "You must have at least one\ntunnel in the list,to use the autostart"
        ),
        "export_tl_info": _("No Tunnels in List for Export"),
        "start_tl_info": _("Click to start selected Wireguard Tunnel"),
        "rename_tl_info": _("To rename a tunnel, at least one must be in the list"),
        "trash_tl_info": _("No tunnels to delete in the list"),
        "list_auto_info": _(
            "To use the autostart, a tunnel must be selected from the list"
        ),
        "download": _("Click to download new version"),
    }