"""Change application theme"""
priority = 0
from tqdm import tqdm

from lxml import etree

def apply(config: dict) -> bool:
    main_color = config["theme"]["colors"]["primary"]
    splash_color = config["theme"]["colors"]["secondary"]
    gradient_from = config["theme"]["gradient"]["from"]
    gradient_to = config["theme"]["gradient"]["to"]

    # No connection alert coolor
    with open("./decompiled/assets/no_connection.html", "r", encoding="utf-8") as file:
        file_contents = file.read()

    new_contents = file_contents.replace("#f04e4e", main_color)

    with open("./decompiled/assets/no_connection.html", "w", encoding="utf-8") as file:
        file.write(new_contents)

    # For logo
    drawable_types = ["", "-night"]

    for drawable_type in drawable_types:
        # Application logo gradient colors
        file_path = f"./decompiled/res/drawable{drawable_type}/$logo__0.xml"

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

        # Change attributes with namespace
        root.set(f"{{{config['xml_ns']['android']}}}startColor", gradient_from)
        root.set(f"{{{config['xml_ns']['android']}}}endColor", gradient_to)

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

        # Application logo anim color
        file_path = f"./decompiled/res/drawable{drawable_type}/$logo_splash_anim__0.xml"

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

        # Finding "path"
        for el in root.findall("path", namespaces=config['xml_ns']):
            name = el.get(f"{{{config['xml_ns']['android']}}}name")
            if name == "path":
                el.set(f"{{{config['xml_ns']['android']}}}fillColor", splash_color)

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

    return True
