#!/usr/bin/env python
import os
import json
from config import PATH_PARTIAL, PATH_SRC, PATH_THEME, PATH_THEME_DEST, \
    PATH_DEST, FILE_SITE, THEME
from chevron import render
from typing import Dict
from shutil import copytree, rmtree


DEF_THEME = 'shop'


def read_json(json_file:str) -> Dict:
    """ read site.json 
    
    """
    with open(json_file, "rt") as fh:
        val = json.loads(fh.read())
        val['lambdas'] = {
            'equal_output': equal_output,
        }
        return val
    return {}


def build_file(hash, file:str) -> str:
    """
    @file: str filename of mustache
    @return: str html populated.
    """
    with open(file, "rt") as fh:
        return render(template=fh, data=hash, partials_path=PATH_PARTIAL)


def build_all():
    # theme
    global THEME
    if not THEME:
        THEME = DEF_THEME
    theme_src_dir = os.path.join(PATH_THEME, THEME)
    theme_dest_dir = PATH_THEME_DEST
    # remote old theme
    try:
        rmtree(theme_dest_dir)
    except Exception:
        pass
    
    # copy theme
    try:
        copytree(theme_src_dir, theme_dest_dir)
    except Exception as e:
        print('ERROR: theme error:', e)
        exit(-1)

    hash = read_json(FILE_SITE)
    for r, _, fl in os.walk(PATH_SRC):
        for f in fl:
            rpath = os.path.join(r, f)
            fn, _ = os.path.splitext(f)
            hash['file'] = fn
            html_str = build_file(hash, rpath)
            if not html_str:
                print('WARNING: empty output:', rpath)
            rhtml = os.path.join(PATH_DEST, '{}.html'.format(fn))
            with open(rhtml, 'wt') as fh:
                fh.write(html_str)


def equal_output(text, render):
    """ 
    mustache lambda: 实现三元语义
    a==b?c:d
    渲染后，如果 a == b 则 最终渲染 c 否则 最终渲染 d
    """
    result = render(text)
    parts = result.split("?")
    compares = parts[0].split("==")
    values = parts[1].split(":")
    return values[0].strip() if compares[0].strip() == compares[1].strip() else values[1].strip()


if __name__ == '__main__':
    build_all()

"""
    ,{
		"text": "代理加盟",
		"url": "agents.html"
	},{
		"text": "下载",
		"url": "https://twong.shotshock.shop/mobilex/download"
	}
"""