#!/usr/bin/env python3
"""
   Generate javascript and move assets
"""
import sys
import os
from os import makedirs, symlink, remove
from os.path import dirname, isdir, relpath, islink
try:
    import mkcmdlinegame
except ImportError:
    from os.path import join, realpath
    sys.path.append(
        join(dirname(dirname(realpath(__file__))), 'lib', 'python3')
    )
    import mkcmdlinegame

USAGE = (
    "Build/export the game in html/css/js format.\n"
    "BASIC USAGE (for testing a game in project dir):\n"
    " %s <gamedir> <tgt_dir>\n"
    "OPTIONS:\n"
    " -t is for writing trace\n"
    "\nNext options allows to compile the game.\n"
    "USAGE:\n"
    " %s <gamedir> <tgt_dir> [-t] [-transpile|-minify|-css|-html] [-only]\n"
    "OPTIONS:\n"
    " -transpile : (step 1a) transpile js for old browsers compatibility\n"
    " -css       : (step 1b) autoprefix css properties\n"
    " -minify    : (step 2) uglify js code\n"
    " -html      : (step 3) generate all-in-one html file\n"
    "Each step depends on the previous ones.\n"
    "To re-execute only one step use '-only'.\n"
    "Therefore you probably need no more than the option '-html'.\n"
    "\nENVIRONMENT VARIABLES FOR DEBUGGING:\n"
    "  'DEBUG=t' shows most of in processing params\n"
    "  'DEBUG_SKIP=postcss' disable css minifying\n"
    "  'DEBUG_SKIP=uglifyjs' disable js minifying\n"
    "  'DEBUG_SKIP=babel,uglifyjs' disable transpiling\n"
    "  'DEBUG_SKIP=nodejs' disable all node things\n"
)


def rsymlink(src, dst):
    """ make portable symbolic link with a relative path """
    orig = relpath(src, dirname(dst))
    if os.environ.get('DEBUG', False):
        print('symlink %s to %s' % (orig, dst))
    symlink(orig, dst)


def _link_dirs_in_project(params, dirs):
    for dname in dirs:
        if not isdir(params['%s_dir' % dname]):
            if not isdir(params['target_%s_dir' % dname]):
                makedirs(params['target_%s_dir' % dname])
            if islink(params['%s_dir' % dname]):
                remove(params['%s_dir' % dname])
            rsymlink(params['target_%s_dir' % dname], params['%s_dir' % dname])


def _main(gamedir, tgt, opts):
    if not isdir(tgt):
        makedirs(tgt)
    params = mkcmdlinegame.build_params.get_project_parameters(gamedir, tgt)
    _link_dirs_in_project(params, ['js', 'img', 'sound', 'music', 'engine'])
    do_all = '-all' in opts
    only = not do_all and '-only' in opts
    all_in_one_html = transpile = postcss = minify = do_all
    all_in_one_html |= '-html' in opts
    transpile |=  '-transpile' in opts
    postcss |= '-css' in opts
    minify |= '-minify' in opts
    if not only:
        transpile |=  minify
        postcss |= minify
    if os.environ.get('DEBUG', False):
        from pprint import pprint
        pprint(params)
    if do_all or transpile or postcss or minify:
        mkcmdlinegame.nodejs.install_deps()
    if not only:
        build_data = mkcmdlinegame.build.build(params)
        if not build_data:
            exit(1)
        if '-t' in opts:
            build_data['line_follower'].write_trace()
    if transpile:
        mkcmdlinegame.build.transpilejs(params)
    if postcss:
        mkcmdlinegame.build.postcss(params)
    if minify:
        mkcmdlinegame.build.minifyjs(params)
    if all_in_one_html:
        mkcmdlinegame.build.all_in_one_html(params)


if __name__ == '__main__':
    GAMEDIR = False
    TARGET = False
    OPTS = {}
    for arg in sys.argv[1:]:
        if arg in ['-t', '-transpile']:
            OPTS[arg] = 1
        elif not GAMEDIR:
            GAMEDIR = arg
        elif not TARGET:
            TARGET = arg
        else:
            OPTS[arg] = arg
    if '-h' in sys.argv[1:] or '--help' in sys.argv[1:] or not (
            GAMEDIR and TARGET):
        print(USAGE)
        exit(1)
    _main(GAMEDIR, TARGET, OPTS)
