"""
Build script for Vignette.
Mostly helps for translation.
"""
import sys
import os
import shutil
import json
from copy import copy

root_dir = os.path.dirname(os.path.realpath(__file__))
source_dir = root_dir + "/source"
langs_dir = root_dir + "/i18n"
build_dir = root_dir + "/build"

base_files = ['index.html', 'licence.html', 'questions.html', 'logo_g.svg']
SCRIPT_DEFAULT_ORIENTATION = "horizontal"


def translate(file_path, strings):
    # load file content
    with open(file_path, "r") as f:
        content = f.read()
    
    # replace each string
    for trans_str in strings.keys(): 
        trans_key = "__" + trans_str + "__"
        content = content.replace(trans_key, strings[trans_str])

    # overwrite file
    with open(file_path, "w") as f:
        f.write(content)

def lang_menu(current_lang, langs):
    li_menu = ""
    for lang in langs:
        if lang != current_lang:
            li_menu += "<li><a href=\"../" + lang + "\">" + lang + "</a></li>"

    menu_infos = {
        "LANGUAGE_DROPDOWN_MENU": li_menu,
        "LANGUAGE_DROPDOWN_MENU_LABEL": current_lang
    }
    return menu_infos

def sort_args(args):
    print(args)
    if len(args) == 1:
        return SCRIPT_DEFAULT_ORIENTATION, None
    if len(args) == 2:   # orientation
        return get_orientation(args[1]), None
    if len(args) == 3:   # orientation
        return get_orientation(args[1]), get_default_lang(args[2])

def get_orientation(user_orientation):
    if user_orientation == "none" or user_orientation == "vertical" or user_orientation == "horizontal":
        return user_orientation
    elif user_orientation == "":
        return SCRIPT_DEFAULT_ORIENTATION
    else:
        print ("Wrong orientation: " + user_orientation + ". Using " + SCRIPT_DEFAULT_ORIENTATION + ".")
        return SCRIPT_DEFAULT_ORIENTATION

def get_default_lang(user_def_lang):
    if user_def_lang == "":
        return None
    else:
        return user_def_lang


## main script
if __name__ == "__main__":
    url_orientation, default_lang = sort_args(sys.argv)

    # erase and replace the build dir
    if os.path.isdir(build_dir):
        shutil.rmtree(build_dir)
        os.mkdir(build_dir)
    
    # Copy common directories
    for dir_ in ['img', 'scr', 'theme']:
        shutil.copytree(source_dir + '/' + dir_, build_dir + '/' + dir_)

    # load langs
    langs = []
    for lang in os.listdir(langs_dir):
        if (os.path.isdir(langs_dir + '/' + lang)):
            langs.append(lang)

    for lang in langs:
        print(lang)
        source_lang_dir = langs_dir + '/' + lang
        build_lang_dir = build_dir + '/' + lang
        os.mkdir(build_lang_dir)

        # copy specific files in build dir
        shutil.copy(source_lang_dir + "/strings.js", build_lang_dir )
        if os.path.isfile(source_lang_dir + "/example_vignette.png"):
            shutil.copy(source_lang_dir + "/example_vignette.png", build_lang_dir )

        # build the menu
        langs_menu_dict = lang_menu(lang, langs)

        # copy common files (still to translate) in build dir and replace strings in html files
        with open(source_lang_dir + '/html_translations.json') as f:
            translation = json.load(f)

        for file_ in base_files:
            source = source_dir + '/files/' + file_
            target = build_lang_dir + '/' + file_
            shutil.copy(source, target)
            print (target)

            file_trans = copy(translation['common'])
            file_trans.update(translation[file_])
            file_trans.update(langs_menu_dict)
            file_trans.update({"URL_ORIENTATION": url_orientation})

            translate(target, file_trans)

        # build HTML homepage (?)
        if lang == default_lang:
            # copy default lang homepage to root dir
            source = target = build_lang_dir + '/index.html'
            target = build_dir + "/index.html"
            shutil.copy(source, target)
            #replace ../ paths by ./
            with open(target, "r") as f:
                content = f.read()
            content = content.replace("../", "./")
            content = content.replace("licence.html", lang + "/licence.html")
            content = content.replace("questions.html", lang + "/questions.html")
            content = content.replace("strings.js", lang + "/strings.js")
            content = content.replace("./logo_g.svg", lang + "/logo_g.svg")
            if os.path.isfile(source_lang_dir + "/example_vignette.png"):
                content = content.replace("example_vignette.png", lang + "/example_vignette.png")
            # overwrite file
            with open(target, "w") as f:
                f.write(content)