#!/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 _("removes the current word from 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:
            self.env["runtime"]["OutputManager"].present_text(
                _("pyenchant is not installed"), interrupt=True
            )
            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 not curr_word.isspace():
            if self.spellChecker.is_removed(curr_word):
                self.env["runtime"]["OutputManager"].present_text(
                    _("{0} is not in the dictionary").format(
                        curr_word,
                    ),
                    sound_icon="Cancel",
                    interrupt=True,
                )
            else:
                self.spellChecker.remove(curr_word)
                self.env["runtime"]["OutputManager"].present_text(
                    _("{0} removed").format(
                        curr_word,
                    ),
                    sound_icon="Accept",
                    interrupt=True,
                )

    def set_callback(self, callback):
        pass
