"""
syntax: "update"
syntax_description: ""
---
Discord Package Botをアップデートします。
"""

import os
import shlex
import subprocess
import zipfile
from glob import glob

import requests
from colorama import Fore, Style  # , Back

from .utils import token


def download_zip(version):
    tags = requests.get(
        "https://api.github.com/repos/discord-package-bot/discord-package-bot/tags",
        headers={"authorization": token.github_authorization},
    )
    for tag in tags.json():
        tag_name = tag.get("name").replace("v", "")
        if tag_name == version:
            print(
                f"{Fore.LIGHTBLACK_EX}バージョン{Style.BRIGHT}{version}{Style.NORMAL}をダウンロードします。{Fore.RESET}"
            )
            zip_url = tag.get("zipball_url")
            with requests.get(
                zip_url,
                headers={"authorization": token.github_authorization},
                stream=True,
            ) as resp:
                with open(".update-tmp.zip", "wb") as f:
                    for chunk in resp.iter_content(chunk_size=1024):
                        if chunk:
                            f.write(chunk)
            return tag["commit"]["sha"], tag_name


def unzip():
    with zipfile.ZipFile(".update-tmp.zip", "r") as zip_ref:
        zip_ref.extractall(".update-tmp")
    os.remove(".update-tmp.zip")


def move_tmp_file():
    for raw_file in glob("./.update-tmp/*/**/*", recursive=True):
        if os.path.isdir(raw_file):
            continue
        file = raw_file.replace("\\", "/").split("/", 3)[-1]
        os.replace(raw_file, "./" + file)


def delete_files():
    os.remove("savedata/new-version")
    subprocess.run(shlex.split("rm -rf ./.update-tmp"))


def update_files(commit_sha, tag_name):
    with open("./savedata/commit-sha", "w") as f:
        f.write(commit_sha)
    with open("./savedata/version", "w") as f:
        f.write(tag_name.replace("v", ""))


def main():
    if not os.path.exists("savedata/new-version"):
        print(f"{Fore.RED}新しいバージョンはありません。{Fore.RESET}")
        return
    with open("savedata/new-version") as f:
        new_version = f.read()
    commit_sha, tag_name = download_zip(new_version)
    unzip()
    move_tmp_file()
    delete_files()
    update_files(commit_sha, tag_name)
    print(f"{Fore.GREEN}アップデートが完了しました！{Fore.RESET}")

"""
syntax: "update"
syntax_description: ""
---
Discord Package Botをアップデートします。
"""

import os
import shlex
import subprocess
import zipfile
from glob import glob

import requests
from colorama import Fore, Style  # , Back

from .utils import token


def download_zip(version):
    tags = requests.get(
        "https://api.github.com/repos/discord-package-bot/discord-package-bot/tags",
        headers={"authorization": token.github_authorization},
    )
    for tag in tags.json():
        tag_name = tag.get("name").replace("v", "")
        if tag_name == version:
            print(
                f"{Fore.LIGHTBLACK_EX}バージョン{Style.BRIGHT}{version}{Style.NORMAL}をダウンロードします。{Fore.RESET}"
            )
            zip_url = tag.get("zipball_url")
            with requests.get(
                zip_url,
                headers={"authorization": token.github_authorization},
                stream=True,
            ) as resp:
                with open(".update-tmp.zip", "wb") as f:
                    for chunk in resp.iter_content(chunk_size=1024):
                        if chunk:
                            f.write(chunk)
            return tag["commit"]["sha"], tag_name


def unzip():
    with zipfile.ZipFile(".update-tmp.zip", "r") as zip_ref:
        zip_ref.extractall(".update-tmp")
    os.remove(".update-tmp.zip")


def move_tmp_file():
    for raw_file in glob("./.update-tmp/*/**/*", recursive=True):
        if os.path.isdir(raw_file):
            continue
        file = raw_file.replace("\\", "/").split("/", 3)[-1]
        os.replace(raw_file, "./" + file)


def delete_files():
    os.remove("savedata/new-version")
    subprocess.run(shlex.split("rm -rf ./.update-tmp"))


def update_files(commit_sha, tag_name):
    with open("./savedata/commit-sha", "w") as f:
        f.write(commit_sha)
    with open("./savedata/version", "w") as f:
        f.write(tag_name.replace("v", ""))


def main():
    if not os.path.exists("savedata/new-version"):
        print(f"{Fore.RED}新しいバージョンはありません。{Fore.RESET}")
        return
    with open("savedata/new-version") as f:
        new_version = f.read()
    commit_sha, tag_name = download_zip(new_version)
    unzip()
    move_tmp_file()
    delete_files()
    update_files(commit_sha, tag_name)
    print(f"{Fore.GREEN}アップデートが完了しました！{Fore.RESET}")

syntax: "update" syntax_description: "" --- Discord Package Botをアップデートします。 # , Back