#!/usr/bin/env python
import os
import json
import toml

from typing import Dict
from chevron import render
from shutil import copytree, rmtree
from config import PATH_PARTIAL, PATH_SRC, PATH_THEME, PATH_THEME_DEST, \
    PATH_DEST, FILE_SITE, DEF_THEME


def read_config(file: str) -> Dict:
    """
    @api {} / read config
    @apiName read_config
    @apiGroup function

    @apiParam {string} file filename of config
    @apiSuccess {dict} config dict reflect to the config file
    @apiError FileNotFound FileUnaccessable FileParseError
    """
    _, ext = os.path.splitext(file)
    loader = toml.loads if ext.lower() == '.toml' else json.loads
    with open(file, 'rt') as fh:
        val = loader(fh.read())
        val['lambdas'] = {
            'equal_output' : equal_output,
        }
        return val
    return {}


def build_file(hash, file:str) -> str:
    """
    build a single mustache file

    @hash: parameters
    @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():
    # load config
    hash = read_config(FILE_SITE)
    site = hash.get('site')
    if not site:
        print('{} error'.format(FILE_SITE))
        exit(-1)

    # theme    
    if not site.get('theme'):
        site['theme'] = DEF_THEME
    theme_src_dir = os.path.join(PATH_THEME, site.get('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(-2)

    for r, _, fl in os.walk(PATH_SRC):
        for f in fl:
            name, ext = os.path.splitext(f)
            if ext.lower() != '.mustache':
                continue

            fullname = os.path.join(r, f)
            hash['file'] = '{}.html'.format(name)
            html_str = build_file(hash, fullname)
            if not html_str:
                print('WARNING: empty output:', fullname)
            fullhtml = os.path.join(PATH_DEST, '{}.html'.format(name))
            with open(fullhtml, '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()
