import logging
import os
import platform
import shutil
import time
import urllib3

from threading import Thread
from urllib3 import PoolManager

FORMAT = "%(asctime)s - %(levelname)s - %(message)s"
logging.basicConfig(format=FORMAT, level=logging.INFO)

URL = "http://et.thegux.fr/jaymod/"
FILES = (
    "1944_beach.pk3",
    "baserace.pk3",
    "caen.pk3",
    "goldendunk_a2.pk3",
    "jaymod-2.2.0.pk3",
    "mlb_temple.pk3",
    "nfl_b2.pk3",
    "saberpeak_final.pk3",
    "supergoldrush_final.pk3",
    "supply_depot_2.pk3",
    "tc_base.pk3",
    "v2base_te.pk3",
    "venice.pk3",
)


def get_files(http: PoolManager, filename: str, outdir: str):
    with open(os.path.join(outdir, filename), "wb") as out:
        r = http.request("GET", f"{URL}/{filename}", preload_content=False)
        shutil.copyfileobj(r, out)


def create_jaymod_directory() -> str:
    name = platform.system()
    if name == "Windows":
        path = os.path.join(
            "C:", "Program Files (x86)", "Wolfenstein - Enemy Territory", "jaymod"
        )
        os.makedirs(path, exist_ok=True)
        return path
    raise Exception("platform not supported")


if __name__ == "__main__":
    start = time.perf_counter()
    logging.info("installing Thegux Jaymod...")

    try:
        jaymod_dir = create_jaymod_directory()
    except Exception as e:
        logging.fatal(e)
        exit(1)

    threads = []
    http = urllib3.PoolManager()

    for f in FILES:
        t = Thread(target=get_files, args=[http, f, jaymod_dir])
        threads.append(t)
        t.start()

    for t in threads:
        t.join()

    logging.info(f"elapsed time: {time.perf_counter() - start:.2f}s")
