# Change application theme

import re


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"
        with open(file_path, "r", encoding="utf-8") as file:
            content = file.read()

        pattern = r'android:startColor="(#[0-9a-fA-F]{8})"\s+android:endColor="(#[0-9a-fA-F]{8})"'

        def replace_colors(match):
            return (
                f'android:startColor="{gradient_from}" android:endColor="{gradient_to}"'
            )

        new_content = re.sub(pattern, replace_colors, content).replace("\n ", "")

        with open(file_path, "w", encoding="utf-8") as file:
            file.write(new_content)

        # Application logo anim color
        file_path = f"./decompiled/res/drawable{drawable_type}/$logo_splash_anim__0.xml"
        with open(file_path, "r", encoding="utf-8") as file:
            content = file.read()

        pattern = r'android:name="path" android:fillColor="(#[0-9a-fA-F]{8})"'

        def replace_colors(match):
            return f'android:name="path" android:fillColor="{splash_color}"'

        new_content = re.sub(pattern, replace_colors, content).replace("\n  ", " ", 1)

        with open(file_path, "w", encoding="utf-8") as file:
            file.write(new_content)

    return True
