"""Добавляет всплывающее окно при первом входе

"welcome": {
  "enabled": true,
  "title": "Anixarts",
  "description": "Описание",
  "link_text": "МЫ В TELEGRAM",
  "link_url": "https://t.me/http_teapod",
  "skip_text": "Пропустить",
  "title_bg_color": "#FFFFFF"
}
"""

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

from pydantic import Field

from utils.config import PatchTemplate
from utils.smali_parser import (find_and_replace_smali_line, get_smali_lines,
                                save_smali_lines)


class Patch(PatchTemplate):
    priority: int = Field(frozen=True, exclude=True, default=0)

    title: str = Field("Anixarts", description="Заголовок")
    title_color: str = Field("#FF252525", description="Цвет заголовка")

    title_bg_color: str = Field("#FFCFF04D", description="Цвет фона заголовка")
    body_bg_color: str = Field("#FF252525", description="Цвет фона окна")

    description: str = Field("Описание", description="Описание")
    description_color: str = Field("#FFFFFFFF", description="Цвет описания")

    skip_text: str = Field("Пропустить", description="Текст кнопки пропустить")
    skip_color: str = Field("#FFFFFFFF", description="Цвет кнопки пропустить")

    link_text: str = Field("МЫ В TELEGRAM", description="Текст ссылки")
    link_color: str = Field("#FFCFF04D", description="Цвет ссылки")
    link_url: str = Field("https://t.me/http_teapod", description="Ссылка")

    def encode_text(self, text: str) -> str:
        return '+'.join([parse.quote(i) for i in text.split(' ')])

    def apply(self, base: Dict[str, Any]) -> bool:
        # Добавление ресурсов окна первого входа
        shutil.copy("./resources/avatar.png", "./decompiled/assets/avatar.png")
        shutil.copy(
            "./resources/OpenSans-Regular.ttf",
            "./decompiled/assets/OpenSans-Regular.ttf",
        )
        for subdir in ["about/", "authorization/"]:
            shutil.copytree("./resources/smali_classes4/com/swiftsoft/"+subdir, "./decompiled/smali_classes4/com/swiftsoft/"+subdir)

        # Привязка к первому запуску
        file_path = "./decompiled/smali_classes3/com/swiftsoft/anixartd/ui/activity/MainActivity.smali"
        method = "invoke-super {p0}, Lmoxy/MvpAppCompatActivity;->onResume()V"
        lines = get_smali_lines(file_path)
        lines = find_and_replace_smali_line(
            lines,
            method,
            method
            + "\ninvoke-static {p0}, Lcom/swiftsoft/about/$2;->oooooo(Landroid/content/Context;)Ljava/lang/Object;",
        )
        save_smali_lines(file_path, lines)

        # Замена ссылки
        file_path = "./decompiled/smali_classes4/com/swiftsoft/about/$4.smali"
        lines = get_smali_lines(file_path)
        lines = find_and_replace_smali_line(
            lines,
            "const-string v0, \"https://example.com\"",
            'const-string v0, "' + self.link_url + '"',
        )
        save_smali_lines(file_path, lines)

        # Настройка всплывающго окна
        file_path = "./decompiled/smali_classes4/com/swiftsoft/about/$2.smali"
        lines = get_smali_lines(file_path)
        for replacement in [
            ('const-string v5, "#FF252525" # Title color', f'const-string v5, "{self.title_color}"'),
            ('const-string v7, "#FFFFFFFF" # Description color', f'const-string v7, "{self.description_color}"'),
            ('const-string v8, "#FFCFF04D" # Link color', f'const-string v8, "{self.link_color}"'),
            ('const-string v9, "#FFFFFFFF" # Skip color', f'const-string v9, "{self.skip_color}"'),
            ('const-string v5, "#FF252525" # Body background', f'const-string v5, "{self.body_bg_color}"'),
            ('const-string v10, "#FFCFF04D" # Title background', f'const-string v10, "{self.title_bg_color}"'),
            ('const-string v12, "Title"', f'const-string v12, "{self.encode_text(self.title)}"'),
            ('const-string v11, "Description"', f'const-string v11, "{self.encode_text(self.description)}"'),
            ('const-string v12, "URL"', f'const-string v12, "{self.link_text.encode('unicode-escape').decode()}"'),
            ('const-string v12, "Skip"', f'const-string v12, "{self.skip_text.encode('unicode-escape').decode()}"')
        ]: lines = find_and_replace_smali_line(lines, *replacement)
        save_smali_lines(file_path, lines)

        return True
