"""
        Меняет порядок вкладок в панели навигации

"replace_navbar": {
  "enabled": true,
  "items": ["home", "discover", "feed", "bookmarks", "profile"]
}
"""

priority = 0

# imports
from lxml import etree
from tqdm import tqdm


# Patch
def apply(config: dict) -> bool:
    file_path = "./decompiled/res/menu/bottom.xml"

    parser = etree.XMLParser(remove_blank_text=True)
    tree = etree.parse(file_path, parser)
    root = tree.getroot()

    items = root.findall("item", namespaces=config['xml_ns'])

    def get_id_suffix(item):
        full_id = item.get(f"{{{config['xml_ns']['android']}}}id")
        return full_id.split("tab_")[-1] if full_id else None

    items_by_id = {get_id_suffix(item): item for item in items}
    existing_order = [get_id_suffix(item) for item in items]

    ordered_items = []
    for key in config['items']:
        if key in items_by_id:
            ordered_items.append(items_by_id[key])

    extra = [i for i in items if get_id_suffix(i) not in config['items']]
    if extra:
        tqdm.write("⚠Найдены лишние элементы: " + str([get_id_suffix(i) for i in extra]))
        ordered_items.extend(extra)

    for i in root.findall("item", namespaces=config['xml_ns']):
        root.remove(i)

    for item in ordered_items:
        root.append(item)

    tree.write(file_path, pretty_print=True, xml_declaration=True, encoding="utf-8")

    return True
