import requests, json, zipfile, os, glob

if os.path.isdir("../static/ruffle/"):
    print("Flash is already downloaded, clearing old directory and updating...")
    rm = glob.glob("../static/ruffle/*")
    for x in rm:
        os.remove(x)
else:
    print("Flash is not downloaded yet, creating directory...")
    os.mkdir("../static/ruffle/")

releases = requests.get("https://api.github.com/repos/ruffle-rs/ruffle/releases?per_page=1")
releasesJsonified = json.loads(releases.text)

for asset in releasesJsonified[0]["assets"]:
    if "web-selfhosted" in asset["browser_download_url"]:
        newFlashFiles = requests.get(asset["browser_download_url"])
        flashDumped = open("flash.zip", "wb+")
        flashDumped.write(newFlashFiles.content)

        flashZip = zipfile.ZipFile("flash.zip", "r")
        flashZip.extractall("../static/ruffle/")

        rmglob = glob.glob("../static/ruffle/*.map")
        rm = ["../static/ruffle/README.md",
              "../static/ruffle/LICENSE_MIT",
              "../static/ruffle/LICENSE_APACHE",
              "../static/ruffle/package.json"]
        for item in rmglob:
            rm.append(item)

        for item in rm:
            os.remove(item)

        flashZip.close()

        os.remove("flash.zip")

        print("Flash was successfully downloaded and extracted")
        exit()

print("Flash not found, download it manually at https://github.com/ruffle-rs/ruffle/releases")
