#!/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

initialized = False
try:
    import enchant

    initialized = True
except Exception as e:
    pass


class command:
    def __init__(self):
        self.language = ""
        self.spellChecker = None

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

    def shutdown(self):
        pass

    def get_description(self):
        return _("adds the current word to the exceptions dictionary")

    def update_spell_language(self):
        self.spellChecker = enchant.Dict(
            self.env["runtime"]["SettingsManager"].get_setting(
                "general", "spell_check_language"
            )
        )
        self.language = self.env["runtime"]["SettingsManager"].get_setting(
            "general", "spell_check_language"
        )

    def run(self):
        if not initialized:
            return
        if (
            self.env["runtime"]["SettingsManager"].get_setting(
                "general", "spell_check_language"
            )
            != self.language
        ):
            try:
                self.update_spell_language()
            except Exception as e:
                return
        cursor_pos = self.env["runtime"][
            "CursorManager"
        ].get_review_or_text_cursor()
        # get the word
        new_content = self.env["screen"]["new_content_text"].split("\n")[
            cursor_pos["y"]
        ]
        x, y, curr_word, end_of_screen, line_break = (
            word_utils.get_current_word(cursor_pos["x"], 0, new_content)
        )
        curr_word = curr_word.strip(
            string.whitespace + r'!"#$%&\()*+,-./:;<=Â?@[\\]^_{|}~'
        )

        if curr_word != "":
            if self.spellChecker.is_added(curr_word):
                self.env["runtime"]["OutputManager"].present_text(
                    _("{0} is already in dictionary").format(
                        curr_word,
                    ),
                    sound_icon="Cancel",
                    interrupt=True,
                )
            else:
                self.spellChecker.add(curr_word)
                self.env["runtime"]["OutputManager"].present_text(
                    _("{0} added to dictionary").format(
                        curr_word,
                    ),
                    sound_icon="Accept",
                    interrupt=True,
                )

    def set_callback(self, callback):
        pass
