import uuid

from components.navigable_list import NavigableList
from bot import bot
from constants import callback_name_list
from decorators.callback import callback

navigable_lists = []

def find_navigable_list(name):
    for nav in navigable_lists:
        if name in nav.name:
            return nav

def register_navigable_list(chat_id,
                            list,
                            begin,
                            offset = 4,
                            template = """{}""",
                            indexed = False,
                            additional_buttons = None,
                            in_place = True,
                            column=1):
    navigable_list_name = str(uuid.uuid4().hex)[:16]
    while find_navigable_list(navigable_list_name) != None:
        navigable_list_name = str(uuid.uuid4().hex)[:16]
    nav = NavigableList(navigable_list_name, list, offset, template, indexed, additional_buttons, in_place, column)
    navigable_lists.append(nav)
    nav.last_message = nav.navigate(bot, chat_id, begin)

@callback(callback_name_list["navigatecallback"])
def navigate_callback(callback_id, message, **kwargs):
    chat_id = kwargs.get("chat_id")
    command, name, begin = message.split(" ")
    begin = int(begin)
    nav = find_navigable_list(name)
    if nav != None:
        message_id = kwargs.get("message_id", nav.last_message)
        nav.last_message = nav.navigate(bot, chat_id, begin, message_id=message_id)

def get_item(name, begin, offset):
    nav = find_navigable_list(name)
    list = nav.inner_list
    begin = int(begin)
    offset = int(offset)
    position = begin + offset
    if position >= 0 and position < len(list):
        return list[position]