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

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

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


class command:
    def __init__(self):
        pass

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

    def shutdown(self):
        pass

    def get_description(self):
        return _("enables or disables tracking of highlighted text")

    def run(self):
        highlight_mode = self.env["runtime"]["SettingsManager"].get_setting_as_bool(
            "focus", "highlight"
        )
        cursor_mode = self.env["runtime"]["SettingsManager"].get_setting_as_bool(
            "focus", "cursor"
        )
        table_mode = self.env["runtime"]["TableManager"].is_table_mode()
        
        self.env["runtime"]["DebugManager"].write_debug_out(
            f"toggle_highlight_tracking: highlight={highlight_mode}, "
            f"cursor={cursor_mode}, table={table_mode}",
            debug.DebugLevel.INFO
        )

        # Cycle through modes: highlight → cursor → table → highlight
        if highlight_mode and not table_mode:
            # Switch to cursor mode
            self.env["runtime"]["SettingsManager"].set_setting(
                "focus", "highlight", "False"
            )
            self.env["runtime"]["SettingsManager"].set_setting(
                "focus", "cursor", "True"
            )
            self.env["runtime"]["TableManager"].set_table_mode(False)
            self.env["runtime"]["OutputManager"].present_text(
                _("cursor tracking"), sound_icon="", interrupt=True
            )
        elif cursor_mode and not table_mode:
            # Switch to table mode
            self.env["runtime"]["SettingsManager"].set_setting(
                "focus", "highlight", "False"
            )
            self.env["runtime"]["SettingsManager"].set_setting(
                "focus", "cursor", "False"
            )
            self.env["runtime"]["TableManager"].set_table_mode(True)
            self.env["runtime"]["OutputManager"].present_text(
                _("table mode"), sound_icon="", interrupt=True
            )
        else:
            # Switch to highlight mode (default) - also handles stuck table mode
            self.env["runtime"]["SettingsManager"].set_setting(
                "focus", "highlight", "True"
            )
            self.env["runtime"]["SettingsManager"].set_setting(
                "focus", "cursor", "False"
            )
            self.env["runtime"]["TableManager"].set_table_mode(False)
            self.env["runtime"]["OutputManager"].present_text(
                _("highlight tracking"), sound_icon="", interrupt=True
            )

    def set_callback(self, callback):
        pass
