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

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

from fenrirscreenreader.core.i18n import _
from fenrirscreenreader.utils import char_utils


class command:
    def __init__(self):
        pass

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

    def shutdown(self):
        pass

    def get_description(self):
        return _("presents the current character.")

    def run(self):
        self.env["runtime"][
            "CursorManager"
        ].enter_review_mode_curr_text_cursor()

        # In table mode, sync to cell start if cursor is outside current cell
        if self.env["runtime"]["TableManager"].is_table_mode():
            table_info = self.env["runtime"]["TableManager"].get_current_table_cell_info()
            if table_info:
                cursor_pos = self.env["screen"]["newCursorReview"]
                line_text = self.env["runtime"]["ScreenManager"].get_line_text(
                    cursor_pos["y"]
                )
                if line_text:
                    column_start = self.env["runtime"]["TableManager"].get_column_start_position(
                        line_text, table_info["column_index"]
                    )
                    cell_content = table_info["cell_content"]
                    cell_end = column_start + len(cell_content)
                    
                    # If cursor is outside the current cell, move to cell start
                    if (
                        cursor_pos["x"] < column_start or 
                        cursor_pos["x"] >= cell_end
                    ):
                        self.env["screen"]["newCursorReview"]["x"] = column_start

        (
            self.env["screen"]["newCursorReview"]["x"],
            self.env["screen"]["newCursorReview"]["y"],
            curr_char,
        ) = char_utils.get_current_char(
            self.env["screen"]["newCursorReview"]["x"],
            self.env["screen"]["newCursorReview"]["y"],
            self.env["screen"]["new_content_text"],
        )

        char_utils.present_char_for_review(
            self.env,
            curr_char,
            interrupt=True,
            announce_capital=True,
            flush=False,
        )
        # is has attribute it enabled?
        if self.env["runtime"]["SettingsManager"].get_setting_as_bool(
            "general", "hasattributes"
        ):
            cursor_pos = self.env["screen"]["newCursorReview"]

            if not self.env["runtime"]["AttributeManager"].has_attributes(
                cursor_pos
            ):
                return
            self.env["runtime"]["OutputManager"].present_text(
                "has attribute", sound_icon="HasAttributes", interrupt=False
            )

    def set_callback(self, callback):
        pass
