"""
Download.
TODO:
    add option to keep existing files in wheelhouse.
"""
import shutil, os, re, zipfile
from datetime import date
try:
    from pip_dater.util import runtime_output
    from pip_dater.check import get_installed
except:
    from util import runtime_output
    from check import get_installed


def download(yes=False, archive=False, include=None, skip_download=False):
    """Download all the packages and create a script for offline installation."""
    print('Getting and cleaning requirements')
    req_installed = get_installed()
    if yes:
       ans = 'y'
       print('Rebuild wheelhouse forced (--yes flag)')
    else:
       ans = input('Remove and rebuild wheelhouse? (y/n) ')
    if ans.lower() in ('y', 'yes'):
        shutil.rmtree('wheelhouse', ignore_errors=True)
        os.mkdir('wheelhouse')
        with open('wheelhouse\\_packages.txt', 'w') as fw:
            fw.write(req_installed)
        if include:
            print(f"Copying the packages from the specified folder: {include}")
            for filename in os.listdir(include):
                print(f"  {filename}")
                shutil.copy(f"{include}\\{filename}", 'wheelhouse')
        print('Downloading base packages (pip/wheel/setuptools)')
        runtime_output('pip download -d wheelhouse pip wheel setuptools', verbose=True)
        print('Downloading everything else ...')
        if not skip_download:
            runtime_output('pip download -r wheelhouse\\_packages.txt -d wheelhouse',
                           verbose=True)
        # create the install batch file, using the exact file names
        print('\nCreate the install batch file')
        pip        = [x for x in os.listdir('wheelhouse') if re.match(r'pip-\d+', x)][-1]
        wheel      = [x for x in os.listdir('wheelhouse') if re.match(r'wheel-\d+', x)][-1]
        setuptools = [x for x in os.listdir('wheelhouse') if re.match(r'setuptools-\d+', x)][-1]
        txt = (
            "@echo off\n\n"
            "echo **** STEP1: update PIP/SETUPTOOLS/WHEEL ****\n"
            f"python -m pip install wheelhouse\\{pip}\n"
            f"pip install wheelhouse\\{setuptools}\n"
            f"pip install wheelhouse\\{wheel}\n\n"
            "echo **** STEP2: install the libraries ****\n"
            "pip install --no-index --find-links wheelhouse -r wheelhouse\\_packages.txt\n\n"
            "echo **** ALL DONE ****\npause\n")
        with open('offline_install.bat', 'w') as fw:
            fw.write(txt)

        # archive
        if archive:
            print('Archive the wheelhouse folder')
            archive_name = f"wheelhouse_{date.today()}.zip"
            try:
                os.remove(archive_name)
            except:
                pass
            with zipfile.ZipFile(archive_name, 'w', compression=zipfile.ZIP_DEFLATED, compresslevel=6) as zf:
                zf.write('offline_install.bat')
                cursor = '-\\|/'
                for path, _, files in os.walk('wheelhouse'):
                    for fn in files:
                        src_filename = os.path.join(path, fn)
                        zf.write(src_filename)
                        print('   ', cursor[0], '\r', end='')
                        cursor = cursor[1:] + cursor[0]
                print('    ', '\r')

            

##########################
if __name__ == "__main__":
    download(yes=True, archive=True, include='test_include', skip_download=True)
