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

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

from fenrirscreenreader.core import debug
from fenrirscreenreader.core.i18n import _


class HelpManager:
    def __init__(self):
        self.helpDict = {}
        self.tutorialListIndex = None

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

    def shutdown(self):
        pass

    def toggle_tutorial_mode(self):
        self.set_tutorial_mode(not self.env["general"]["tutorialMode"])

    def set_tutorial_mode(self, newTutorialMode):
        if self.env["runtime"]["VmenuManager"].get_active():
            return
        self.env["general"]["tutorialMode"] = newTutorialMode
        if newTutorialMode:
            self.create_help_dict()
            self.env["bindings"][
                str([1, ["KEY_ESC"]])
            ] = "TOGGLE_TUTORIAL_MODE"
            self.env["bindings"][str([1, ["KEY_UP"]])] = "PREV_HELP"
            self.env["bindings"][str([1, ["KEY_DOWN"]])] = "NEXT_HELP"
            self.env["bindings"][str([1, ["KEY_SPACE"]])] = "CURR_HELP"
        else:
            try:
                self.env["bindings"] = self.env["runtime"][
                    "SettingsManager"
                ].get_binding_backup()
            except Exception as e:
                self.env["runtime"]["DebugManager"].write_debug_out(
                    "HelpManager set_tutorial_mode: Error restoring binding backup: "
                    + str(e),
                    debug.DebugLevel.ERROR,
                )

    def is_tutorial_mode(self):
        return self.env["general"]["tutorialMode"]

    def get_formatted_shortcut_for_command(self, command):
        shortcut = []
        raw_shortcut = []
        try:
            raw_shortcut = list(self.env["bindings"].keys())[
                list(self.env["bindings"].values()).index(command)
            ]
            raw_shortcut = self.env["rawBindings"][raw_shortcut]
            # prefer numbers for multitap
            if raw_shortcut[0] in range(2, 9):
                formatted_key = str(raw_shortcut[0]) + " times "
                shortcut.append(formatted_key)
            # prefer metha keys
            for k in [
                "KEY_FENRIR",
                "KEY_SCRIPT",
                "KEY_CTRL",
                "KEY_SHIFT",
                "KEY_ALT",
                "KEY_META",
            ]:
                if k in raw_shortcut[1]:
                    formatted_key = k
                    formatted_key = formatted_key.lower()
                    formatted_key = formatted_key.replace("key_kp", " keypad ")
                    formatted_key = formatted_key.replace("key_", " ")
                    shortcut.append(formatted_key)
                    raw_shortcut[1].remove(k)
            # handle other keys
            for k in raw_shortcut[1]:
                formatted_key = k
                formatted_key = formatted_key.lower()
                formatted_key = formatted_key.replace("key_kp", " keypad ")
                formatted_key = formatted_key.replace("key_", " ")
                shortcut.append(formatted_key)
        except Exception as e:
            return ""
        shortcut = str(shortcut)
        shortcut = shortcut.replace("[", "")
        shortcut = shortcut.replace("]", "")
        shortcut = shortcut.replace("'", "")
        return shortcut

    def get_command_help_text(self, command, section="commands"):
        command_name = command.lower()
        command_name = command_name.split("__-__")[0]
        command_name = command_name.replace("_", " ")
        command_name = command_name.replace("_", " ")
        if command == "TOGGLE_TUTORIAL_MODE":
            command_description = _("toggles the tutorial mode")
        else:
            command_description = self.env["runtime"][
                "CommandManager"
            ].get_command_description(command, section="commands")
        if command_description == "":
            command_description = "no Description available"
        command_shortcut = self.get_formatted_shortcut_for_command(command)
        if command_shortcut == "":
            command_shortcut = "unbound"
        helptext = (
            command_name
            + ", Shortcut "
            + command_shortcut
            + ", Description "
            + command_description
        )
        return helptext

    def create_help_dict(self, section="commands"):
        self.helpDict = {}
        for command in sorted(self.env["commands"][section].keys()):
            self.helpDict[len(self.helpDict)] = self.get_command_help_text(
                command, section
            )
        if len(self.helpDict) > 0:
            self.tutorialListIndex = 0
        else:
            self.tutorialListIndex = None

    def get_help_for_current_index(self):
        if self.tutorialListIndex is None:
            return ""
        return self.helpDict[self.tutorialListIndex]

    def next_index(self):
        if self.tutorialListIndex is None:
            return
        self.tutorialListIndex += 1
        if self.tutorialListIndex >= len(self.helpDict):
            self.tutorialListIndex = 0

    def prev_index(self):
        if self.tutorialListIndex is None:
            return
        self.tutorialListIndex -= 1
        if self.tutorialListIndex < 0:
            self.tutorialListIndex = len(self.helpDict) - 1
