import os
import time
import urllib.request
import zipfile
from pathlib import Path

SCRIPT_FOLDER = Path(__file__).parent
ZIP_FILE_PATH = SCRIPT_FOLDER / "sd.zip"

OUTPUT_DIR = SCRIPT_FOLDER  # files will go into StellarDrive Demo


class ProgressBar:
    def __init__(self, prefix) -> None:
        self.previous = 0
        self.prefix = prefix
        print()

    def update(self, percent):
        percent = round(percent)
        if percent == self.previous:
            return
        self.previous = percent

        print(f"\r{self.prefix} {percent}%", end="")


def download_zip_file():
    URL = "https://drive.usercontent.google.com/download?id=1yaOCiXCGWTfVpBVSDqhW03_SZF5RBAK3&export=download&confirm=t"
    if ZIP_FILE_PATH.exists():
        print("[download] Zip file already downloaded, skipping...")
        return

    print("[download] Downloading!", end="")
    progress_bar = ProgressBar("[download] Progress:")

    def on_progress(block_num, block_size, total_size):
        percent = block_num * block_size / total_size * 100
        progress_bar.update(percent)

    time_start = time.time()
    urllib.request.urlretrieve(URL, ZIP_FILE_PATH, on_progress)
    elapsed = time.time() - time_start
    print(f"\n[download] Finished downloading in about {round(elapsed * 10) / 10}s.")


def extract_zip_file():
    print("[extract] Extracting...")
    with zipfile.ZipFile(ZIP_FILE_PATH, "r") as zf:
        zf.extractall(OUTPUT_DIR)


def rename_artifacts():
    print("[rename] Rename operation starting...")
    os.rename(
        OUTPUT_DIR / "StellarDrive Demo/StellarDrive.exe",
        OUTPUT_DIR / "StellarDrive Demo/GithubDesktop.exe",
    )
    os.rename(
        OUTPUT_DIR / "StellarDrive Demo/StellarDrive_Data",
        OUTPUT_DIR / "StellarDrive Demo/GithubDesktop_Data",
    )


def main():
    download_zip_file()
    extract_zip_file()
    print(
        f"\nDone! Run {OUTPUT_DIR / 'StellarDrive Demo/GithubDesktop.exe'} to play :)"
    )


if __name__ == "__main__":
    main()