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

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

__author__ = "wowlikon <wowlikon@gmail.com>"
__version__ = "1.0.0"
from typing import Any, Dict, List

from lxml import etree
from pydantic import Field
from tqdm import tqdm

from utils.config import PatchTemplate
from utils.smali_parser import get_smali_lines, save_smali_lines, find_smali_line

class Patch(PatchTemplate):
    priority: int = Field(frozen=True, exclude=True, default=0)
    default_compact: bool = Field(True, description="Компактный вид по умолчанию")
    items: List[str] = Field(
        ["home", "discover", "feed", "bookmarks", "profile"],
        description="Список элементов в панели навигации",
    )

    def apply(self, base: Dict[str, Any]) -> 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=base["xml_ns"])

        def get_id_suffix(item):
            full_id = item.get(f"{{{base['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 self.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 self.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=base["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")

        # Изменение компактного вида
        if self.default_compact:
            main_file_path = "./decompiled/smali_classes3/com/swiftsoft/anixartd/ui/activity/MainActivity.smali"
            main_lines = get_smali_lines(main_file_path)

            preference_file_path = "./decompiled/smali_classes3/com/swiftsoft/anixartd/ui/fragment/main/preference/AppearancePreferenceFragment.smali"
            preference_lines = get_smali_lines(preference_file_path)

            main_const = find_smali_line(main_lines, "BOTTOM_NAVIGATION_COMPACT")[-1]
            preference_const = find_smali_line(preference_lines, "BOTTOM_NAVIGATION_COMPACT")[-1]

            main_invoke = find_smali_line(main_lines, "Landroid/content/SharedPreferences;->getBoolean(Ljava/lang/String;Z)Z")[0]
            preference_invoke = find_smali_line(preference_lines, "Landroid/content/SharedPreferences;->getBoolean(Ljava/lang/String;Z)Z")[0]

            main_value = set(find_smali_line(main_lines, "const/4 v7, 0x0"))
            preference_value = set(find_smali_line(preference_lines, "const/4 v7, 0x0"))

            main_target_line = main_value & set(range(main_const, main_invoke))
            preference_tartget_line = preference_value & set(range(preference_const, preference_invoke))

            assert len(main_target_line) == 1 and len(preference_tartget_line) == 1

            main_lines[main_target_line.pop()] = "const/4 v7, 0x1"
            preference_lines[preference_tartget_line.pop()] = "const/4 v7, 0x1"

            save_smali_lines(main_file_path, main_lines)
            save_smali_lines(preference_file_path, preference_lines)

        return True
