#!/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 _("Move Review to the last character on the line")

    def run(self):
        # Check if we're in table mode first
        is_table_mode = self.env["runtime"]["TableManager"].is_table_mode()
        if is_table_mode:
            table_info = self.env["runtime"]["TableManager"].move_to_last_char_in_cell()
            if table_info:
                char_utils.present_char_for_review(
                    self.env,
                    table_info['character'],
                    interrupt=True,
                    announce_capital=True,
                    flush=False,
                )
                self.env["runtime"]["OutputManager"].present_text(
                    _("last character in cell {0}").format(table_info['column_header']),
                    interrupt=False,
                )
            else:
                self.env["runtime"]["OutputManager"].present_text(
                    _("no table data"), interrupt=True, flush=False
                )
            return
        
        # Regular line last character navigation (when not in table mode)
        cursor_pos = self.env["runtime"][
            "CursorManager"
        ].get_review_or_text_cursor()
        self.env["runtime"]["CursorManager"].set_review_cursor_position(
            self.env["screen"]["columns"] - 1, cursor_pos["y"]
        )
        (
            self.env["screen"]["newCursorReview"]["x"],
            self.env["screen"]["newCursorReview"]["y"],
            lastChar,
        ) = char_utils.get_last_char_in_line(
            self.env["screen"]["newCursorReview"]["y"],
            self.env["screen"]["new_content_text"],
        )

        char_utils.present_char_for_review(
            self.env,
            lastChar,
            interrupt=True,
            announce_capital=True,
            flush=False,
        )
        self.env["runtime"]["OutputManager"].present_text(
            _("last character in line"), interrupt=False
        )

    def set_callback(self, callback):
        pass
