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

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

import string

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


class command:
    def __init__(self):
        pass

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

    def shutdown(self):
        pass

    def get_description(self):
        return _("Announces completed words during typing")

    def run(self):
        # is it enabled?
        if not self.env["runtime"]["SettingsManager"].get_setting_as_bool(
            "keyboard", "word_echo"
        ):
            return
        # is navigation?
        if (
            self.env["screen"]["new_cursor"]["x"]
            - self.env["screen"]["old_cursor"]["x"]
            != 1
        ):
            return
        # just when cursor move worddetection is needed
        if not self.env["runtime"][
            "CursorManager"
        ].is_cursor_horizontal_move():
            return
        # for now no new line
        if self.env["runtime"]["CursorManager"].is_cursor_vertical_move():
            return
        # currently writing
        if self.env["runtime"]["ScreenManager"].is_delta():
            return

        # get the word
        new_content = self.env["screen"]["new_content_text"].split("\n")[
            self.env["screen"]["new_cursor"]["y"]
        ]
        x, y, curr_word, end_of_screen, line_break = (
            word_utils.get_current_word(
                self.env["screen"]["new_cursor"]["x"], 0, new_content
            )
        )

        # is there a word?
        if curr_word == "":
            return
        # at the end of a word
        if (
            self.env["screen"]["new_cursor"]["x"] >= len(new_content)
            or not new_content[self.env["screen"]["new_cursor"]["x"]].isspace()
        ):
            return
        # at the end of a word
        if (x + len(curr_word) != self.env["screen"]["new_cursor"]["x"]) and (
            x + len(curr_word) != self.env["screen"]["new_cursor"]["x"] - 1
        ):
            return

        self.env["runtime"]["OutputManager"].present_text(
            curr_word, interrupt=True, flush=False
        )

    def set_callback(self, callback):
        pass
