# -*- coding: utf-8 -*-
"""Prepare the zip file for the model
"""
import os
import shutil
import sys
from refutils import base_to_hs2, base_to_step, base_to_turb
from refutils.dll_utils import get_towerclearance_mblade, clone_dll_repo


if __name__ == '__main__':
    # get ref name
    ci_ref = sys.argv[1]
    print(f'Preparing zip file for {ci_ref}...')
    # script inputs
    mod_dir = '../dtu-10mw-rwt/'  # must end with slash
    zip_name = f'../dtu-10mw-rwt-{ci_ref}'
    basename = 'DTU_10MW_RWT'
    dll_git_url = 'https://gitlab.windenergy.dtu.dk/OpenLAC/control-binary/control-win32.git'
    dll_branch = 'ref_models'
    dll_list = [('dtu_we_controller.dll', 'dtu_we_controller.dll'),
                ('generator_servo.dll', 'generator_servo.dll'),
                ('mech_brake.dll', 'mech_brake.dll'),
                ('servo_with_limits.dll', 'servo_with_limits.dll')]

    # ======= make hawcstab2 and step-wind files =======
    htc_base = mod_dir + f'htc/{basename}.htc'
    kwargs = dict(pitch_f=100, pitch_z=0.7, cut_in=4, cut_out=25, n_wsp=22,
                  gen_min=299.85, gen_max=479.56567, gbr=50, pitch_min=0, opt_lambda=7.5,
                  rate_pow=10000, gen_eff=0.94, p1_f=0.05, p1_z=0.7, p2_f=0.06, p2_z=0.7,
                  gs=2, constant_power=1, dt=40, tstart=100, wsp=24, tint=0.157,
                  tb_wid=180, tb_ht=180)

    # turbulent file
    turb_path = mod_dir + f'htc/{basename}_turb.htc'
    base_to_turb(htc_base, turb_path, **kwargs)

    # hawcstab2
    hs2_path = mod_dir + f'{basename}_hs2.htc'
    base_to_hs2(htc_base, hs2_path, **kwargs)

    # step wind
    step_path = mod_dir + f'htc/{basename}_step.htc'
    base_to_step(htc_base, step_path, **kwargs)

    # ======= create/clean control folder =======
    control_dir = mod_dir + 'control/'  # must end with slash!

    # delete dlls in control repo
    try:  # if control folder exists, delete dlls
        delete_dlls(control_dir)
    except FileNotFoundError:  # if control folder doesn't exist, create it
        os.mkdir(control_dir)

    # ======= download tower clearance =======
    get_towerclearance_mblade(folder=control_dir)

    # ======= get dlls from binary repo =======

    # clone dll repo (will throw error if repo not deleted)
    clone_dll_repo(dll_branch)

    # copy dlls to control repo
    [shutil.copy('control-win32/' + t[0], control_dir + t[1])
     for t in dll_list]

    # ======= make the archive =======
    shutil.make_archive(zip_name, 'zip', mod_dir)


#%%