import os
import requests
import json

import urllib.request

from tqdm import tqdm


class DownloadProgressBar(tqdm):
    def update_to(self, b=1, bsize=1, tsize=None):
        if tsize is not None:
            self.total = tsize
        self.update(b * bsize - self.n)


def download_url(url, output_path):
    with DownloadProgressBar(unit='B', unit_scale=True,
                             miniters=1, desc=url.split('/')[-1]) as t:
        urllib.request.urlretrieve(url, filename=output_path, reporthook=t.update_to)

if __name__ == "__main__":
    data = {}
    print (f"Install dir is {os.path.expandvars(r'%LOCALAPPDATA%')}/ChrisPS")
    if os.path.exists(os.path.expandvars(r'%LOCALAPPDATA%') + '/ChrisPS') is False:
        os.mkdir(os.path.expandvars(r'%LOCALAPPDATA%') + '/ChrisPS')
    if os.path.isfile(os.path.expandvars(r'%LOCALAPPDATA%') + '/ChrisPS/config_chrisps.json'):
        with open(os.path.expandvars(r'%LOCALAPPDATA%') + '/ChrisPS/config_chrisps.json', 'r', encoding='utf8') as json_file:
            data = json.load(json_file)

    version = requests.get('https://chrisps.captain-nwa.ch/version').json()
    if 'version' not in data or float(version) > float(data['version']):
        print ("Your install is out of date, getting latest")
        url = 'https://chrisps.captain-nwa.ch/ChrisPS-latest'
        download_url('https://chrisps.captain-nwa.ch/ChrisPS-latest', os.path.expandvars(r'%LOCALAPPDATA%') + '/ChrisPS/ChrisPS.exe')
        data['version'] = str(version)
        with open(os.path.expandvars(r'%LOCALAPPDATA%') + '/ChrisPS/config_chrisps.json', 'w+') as json_file:
            json.dump(data, json_file)
    print ("Everything okay, starting")
    if os.path.isfile(os.path.expandvars(r'%LOCALAPPDATA%') + '/ChrisPS/ChrisPS.exe'):
        os.execv(os.path.expandvars(r'%LOCALAPPDATA%') + '/ChrisPS/ChrisPS.exe', ['-v'])