#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# Fenrir TTY screen reader
# By Chrys, Storm Dragon, and contributors.

import os

from fenrirscreenreader.core import debug
from fenrirscreenreader.core.i18n import _


class command:
    def __init__(self):
        pass

    def initialize(self, environment):
        self.env = environment

    def shutdown(self):
        pass

    def get_description(self):
        return _("cycles between available keyboard layouts")

    def get_available_layouts(self):
        """Get list of available keyboard layout files"""
        layouts = []

        # Check standard locations for keyboard layouts
        settings_root = "/etc/fenrirscreenreader/"
        if not os.path.exists(settings_root):
            # Fallback to source directory
            import fenrirscreenreader

            fenrir_path = os.path.dirname(fenrirscreenreader.__file__)
            settings_root = fenrir_path + "/../../config/"

        keyboard_path = settings_root + "keyboard/"

        if os.path.exists(keyboard_path):
            for file in os.listdir(keyboard_path):
                if (
                    file.endswith(".conf")
                    and not file.startswith("__")
                    and not file.lower().startswith("pty")
                ):
                    layout_name = file.replace(".conf", "")
                    if layout_name not in layouts:
                        layouts.append(layout_name)

        # Ensure we have at least basic layouts
        if not layouts:
            layouts = ["desktop", "laptop"]
        else:
            layouts.sort()

        return layouts

    def run(self):
        current_layout = self.env["runtime"]["SettingsManager"].get_setting(
            "keyboard", "keyboard_layout"
        )

        # Extract layout name from full path if needed
        if "/" in current_layout:
            current_layout = os.path.basename(current_layout).replace(
                ".conf", ""
            )

        # Get available layouts
        available_layouts = self.get_available_layouts()

        # Find next layout in cycle
        try:
            current_index = available_layouts.index(current_layout)
            next_index = (current_index + 1) % len(available_layouts)
        except ValueError:
            # If current layout not found, start from beginning
            next_index = 0

        next_layout = available_layouts[next_index]

        # Update setting and reload shortcuts
        self.env["runtime"]["SettingsManager"].set_setting(
            "keyboard", "keyboard_layout", next_layout
        )

        # Reload shortcuts with new layout
        try:
            self.env["runtime"]["InputManager"].reload_shortcuts()
            self.env["runtime"]["OutputManager"].present_text(
                _("Switched to {} keyboard layout").format(next_layout),
                interrupt=True,
            )
        except Exception as e:
            self.env["runtime"]["DebugManager"].write_debug_out(
                "Error reloading shortcuts: " + str(e), debug.DebugLevel.ERROR
            )
            self.env["runtime"]["OutputManager"].present_text(
                _("Error switching keyboard layout"), interrupt=True
            )

    def set_callback(self, callback):
        pass
