import imp
import os.path
import StringIO

import config  # @UnusedImport
from fablib import (export_version, do_sync_web, create_config,
                    clean_export_folder, do_sync_comp, sync_install_build, do_create_virtualenv,
                    clean_rsync_folder, rsync_export, get_src_version, sync_build,
                    do_relaunch_server, install_build, do_create_virtualenv_requirement)
from fabric.api import task, env
from fabric.colors import green

def build_source(version):
    print(green("build source with version %s" % version))
    export_path = export_version(iconolab=version)
    export_path_full = os.path.join(export_path,'src')
    build_src(export_path_full)
    (_,version_str) = get_src_version(env.key, src_path)
    return os.path.join(src_path,"dist","%s-%s.tar.gz" % (env.key,version_str))

@task
def relaunch_server(do_collectstatic=True, do_migrate=True, do_check_folder_access=False):
    print("Relaunch server")
    do_relaunch_server(do_collectstatic, do_migrate, env.get('check_folder_access',do_check_folder_access))

@task
def sync_site(version):
    print(green("sync site with version %s" % version))
    build_path = build_source(version)
    res_trans = sync_build(build_path)
    # untar build
    run('tar zxf %s' % res_trans[0])
    # rebuild virtualenv
    requirements_path = os.path.join(res_trans[0][0:-7], env.repos[env.key]['requirements'])
    do_create_virtualenv_requirement(requirements_path, env.remote_path['virtualenv'], env.repos[env.key]['python_version'])
    # add setting path to virtualenv
    ext_path = "import sys; sys.__plen = len(sys.path)\n"
    for l in env.remote_path.get('pythonpath', []):
        ext_path += l + "\n"
    ext_path += "import sys; new=sys.path[sys.__plen:]; del sys.path[sys.__plen:]; p=getattr(sys,'__egginsert',0); sys.path[p:p]=new; sys.__egginsert = p+len(new)"
    put(StringIO.StringIO(ext_path), os.path.join(env.remote_path['virtualenv'], 'lib/python%s/site-packages/_virtualenv_path_extensions.pth'%env.repos[env.key]['python_version']))
    # install build
    install_build(res_trans[0], env.remote_path['virtualenv'])
    # remove build + untared folder
    run('rm -fr "%s" "%s" ' % (res_trans[0], res_trans[0][0:-7]))
    clean_export_folder(export_path)
    relaunch_server()

@task
def create_virtualenv(version):
    print(green("create virtualenv with version %s" % version))
    export_path = export_version(web=version)
    export_path_web = os.path.join(export_path,'web')
    venv_remote_export_path = ""
    try:
        virtualenv_path = os.path.join(export_path_web, "virtualenv")

        venv_remote_export_path = os.path.join(env.remote_path['venv_export'], env.export_prefix, version,"virtualenv")
        rsync_export(virtualenv_path, venv_remote_export_path, env.rsync_filters['venv'])
        do_create_virtualenv(venv_remote_export_path, env.remote_path['virtualenv'])
    finally:
        clean_export_folder(export_path)
        if venv_remote_export_path:
            clean_rsync_folder(venv_remote_export_path)

if len(env.repos) > 1:
    @task
    def sync_platform(version):
        print(green("sync platform with version web %s" % (version)))
        export_path = export_version(web=version)

        export_path_web = os.path.join(export_path,'web')
        do_sync_web(version, export_path_web)

        comp_versions = get_comp_versions_dict(export_path_web)

        for key in [k for k in env.repos if k != 'web']:
            export_path_key = export_version(**{key: comp_versions[key]})
            export_path_comp = os.path.join(export_path_key, key)
            do_sync_comp(key, export_path_comp)
            clean_export_folder(export_path_key)

        create_config(export_path_web)
        clean_export_folder(export_path)
        relaunch_server()
