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

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


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 _("Announces characters as they are typed")

    def run(self):
        # enabled?
        active = self.env["runtime"]["SettingsManager"].get_setting_as_int(
            "keyboard", "charEchoMode"
        )
        # 0 = off
        if active == 0:
            return
        # 2 = caps only
        if active == 2:
            if not self.env["input"]["newCapsLock"]:
                return
        # big changes are no char (but the value is bigger than one maybe the
        # differ needs longer than you can type, so a little strange random
        # buffer for now)
        x_move = abs(
            self.env["screen"]["new_cursor"]["x"]
            - self.env["screen"]["old_cursor"]["x"]
        )
        if x_move > 3:
            return
        if self.env["runtime"]["InputManager"].get_shortcut_type() in ["KEY"]:
            if self.env["runtime"][
                "InputManager"
            ].get_last_deepest_input() in [["KEY_TAB"]]:
                return
        elif self.env["runtime"]["InputManager"].get_shortcut_type() in [
            "BYTE"
        ]:
            if self.env["runtime"]["ByteManager"].get_last_byte_key() in [
                b"	",
                b"\t",
            ]:
                return
        # detect deletion or chilling
        if (
            self.env["screen"]["new_cursor"]["x"]
            <= self.env["screen"]["old_cursor"]["x"]
        ):
            return
        # is there any change?
        if not self.env["runtime"]["ScreenManager"].is_delta():
            return
        # filter unneded space on word begin
        curr_delta = self.env["screen"]["new_delta"]
        if (
            len(curr_delta.strip()) != len(curr_delta)
            and curr_delta.strip() != ""
        ):
            curr_delta = curr_delta.strip()
        self.env["runtime"]["OutputManager"].present_text(
            curr_delta,
            interrupt=True,
            ignore_punctuation=True,
            announce_capital=True,
            flush=False,
        )

    def set_callback(self, callback):
        pass
