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

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

import time

from fenrirscreenreader.core import debug


class MemoryManager:
    def __init__(self):
        self.listStorage = {}

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

    def shutdown(self):
        pass

    def list_storage_valid(self, name, checkIndex=False):
        try:
            if checkIndex:
                index = self.listStorage[name]["index"]
                if index == -1:
                    return self.listStorage[name]["list"] == []
                return self.listStorage[name]["list"][index] is not None
            else:
                return isinstance(self.listStorage[name]["list"], list)
        except Exception as e:
            self.env["runtime"]["DebugManager"].write_debug_out(
                "list_storage_valid " + str(e), debug.DebugLevel.ERROR
            )
        return False

    def add_value_to_first_index(self, name, value):
        if not self.list_storage_valid(name):
            return
        if self.listStorage[name]["maxLength"] is None:
            # Fallback: if maxLength is still None, apply default limit of 1000
            self.listStorage[name]["list"] = [value] + self.listStorage[name][
                "list"
            ][:999]
        else:
            self.listStorage[name]["list"] = [value] + self.listStorage[name][
                "list"
            ][: self.listStorage[name]["maxLength"] - 1]
        self.listStorage[name]["index"] = 0

    def add_index_list(self, name, maxLength=1000, currList=[], curr_index=-1):
        if len(currList) != 0 and (curr_index == -1):
            curr_index = 0
        self.listStorage[name] = {
            "list": currList,
            "index": curr_index,
            "maxLength": maxLength,
        }

    def is_last_index(self, name):
        if not self.list_storage_valid(name):
            return False
        return (
            self.listStorage[name]["index"]
            == len(self.listStorage[name]["list"]) - 1
        )

    def is_first_index(self, name):
        if not self.list_storage_valid(name):
            return False
        return self.listStorage[name]["index"] == 0

    def get_next_index(self, name):
        if not self.list_storage_valid(name):
            return False
        if self.is_index_list_empty(name):
            self.listStorage[name]["index"] = -1
            return False
        self.listStorage[name]["index"] += 1
        if (
            self.listStorage[name]["index"]
            > len(self.listStorage[name]["list"]) - 1
        ):
            self.listStorage[name]["index"] = 0
        return True

    def set_pref_index(self, name):
        if not self.list_storage_valid(name):
            return False
        if self.is_index_list_empty(name):
            self.listStorage[name]["index"] = -1
            return False
        self.listStorage[name]["index"] -= 1
        if self.listStorage[name]["index"] < 0:
            self.listStorage[name]["index"] = (
                len(self.listStorage[name]["list"]) - 1
            )
        return True

    def set_first_index(self, name):
        if not self.list_storage_valid(name):
            return False
        if self.is_index_list_empty(name):
            self.listStorage[name]["index"] = -1
            return False
        self.listStorage[name]["index"] = 0
        return True

    def get_index_list_len(self, name):
        if not self.list_storage_valid(name):
            return 0
        if self.is_index_list_empty(name):
            self.listStorage[name]["index"] = -1
            return 0
        return len(self.listStorage[name])

    def set_last_index(self, name):
        if not self.list_storage_valid(name):
            return False
        if self.is_index_list_empty(name):
            self.listStorage[name]["index"] = -1
            return False
        self.listStorage[name]["index"] = (
            len(self.listStorage[name]["list"]) - 1
        )
        return True

    def clear_current_index_list(self, name):
        if not self.list_storage_valid(name):
            return False
        self.listStorage[name]["list"] = []
        self.listStorage[name]["index"] = -1

    def get_current_index(self, name):
        if not self.list_storage_valid(name):
            return False
        if self.is_index_list_empty(name):
            self.listStorage[name]["index"] = -1
            return False
        try:
            return self.listStorage[name]["index"]
        except Exception as e:
            self.env["runtime"]["DebugManager"].write_debug_out(
                "MemoryManager get_current_index: Error accessing index for "
                + name
                + ": "
                + str(e),
                debug.DebugLevel.ERROR,
            )
            return -1

    def is_index_list_empty(self, name):
        if not self.list_storage_valid(name):
            return False
        return len(self.listStorage[name]["list"]) == 0

    def get_index_list_element(self, name):
        if not self.list_storage_valid(name):
            return None
        if self.is_index_list_empty(name):
            self.listStorage[name]["index"] = -1
            return None
        curr_index = self.get_current_index(name)
        if curr_index == -1:
            return None
        try:
            return self.listStorage[name]["list"][curr_index]
        except Exception as e:
            self.env["runtime"]["DebugManager"].write_debug_out(
                "MemoryManager get_index_list_element: Error accessing element for "
                + name
                + ": "
                + str(e),
                debug.DebugLevel.ERROR,
            )
            return None
