#!/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 "No Description found"

    def run(self):
        # is navigation?
        if (
            not abs(
                self.env["screen"]["old_cursor"]["x"]
                - self.env["screen"]["new_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 start of a word
        if (x + len(curr_word) != self.env["screen"]["new_cursor"]["x"]) and (
            self.env["screen"]["new_cursor"]["x"] != x
        ):
            return

        # Don't interrupt ongoing auto-read announcements
        do_interrupt = True
        if self.env["runtime"]["SettingsManager"].get_setting_as_bool(
            "speech", "auto_read_incoming"
        ):
            do_interrupt = False

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

    def set_callback(self, callback):
        pass
