#!/usr/bin/env node

/**
 * Generate xtemplate function by xtemplate file using kissy xtemplate.
 * @author yiminghe@gmail.com
 */

var argv = require('optimist')
        .demand('t')
        .alias('t', 'tpl')
        .describe('t', 'kissy xtemplate file')
        .alias('m', 'module')
        .describe('m', 'generated kissy module name')
        .describe('e', 'xtemplate file encoding')
        .alias('encoding', 'e')
        .describe('w', 'watch xtemplate file change')
        .boolean('w')
        .alias('watch', 'w')
        .usage('generate kissy module file from kissy xtemplate file.\n' +
        'usage: $0 -t [tpl file] -m [module name]').argv,

    S = require('../build/kissy-nodejs'),

    js_beautify = require('js-beautify').js_beautify,

    fs = require('fs'),
    tpl = argv.tpl,
    path = require('path'),
    encoding = argv.e || 'utf-8';

// S.log('*********** tpl:');
// S.log(tpl);

var tplBaseName = path.basename(tpl, '-tpl.html');

// S.log('*********** tplBaseName:');
// S.log(tplBaseName);

var modulePath = path.resolve(tpl, '../' + tplBaseName + '.js');

// S.log('*********** modulePath:');
// S.log(modulePath);


var codeTemplate = '' +
    '/*\n' +
    '  Generated by kissy-xtemplate.' +
    '*/\n' +
    'KISSY.add({module} function(){\n' +
    'return {code}\n' +
    '});';

var module = argv.module || '';

if (module) {
    module = '"' + module + '",';
}

function my_js_beautify(str) {
    var opts = {"indent_size": "4", "indent_char": " ",
        "preserve_newlines": true, "brace_style": "collapse",
        "keep_array_indentation": false, "space_after_anon_function": true};
    return js_beautify(str, opts);
}

S.use('xtemplate/compiler', function (S, XTemplateCompiler) {

    function compile() {

        var tplContent = fs.readFileSync(tpl, encoding);
        // S.log('*********** tplContent:');
        // S.log(tplContent);

        var code = XTemplateCompiler.compileToStr(tplContent);

        var moduleCode = my_js_beautify(S.substitute(codeTemplate, {
            module: module,
            code: code
        }));

        // S.log(moduleCode);

        fs.writeFileSync(modulePath, moduleCode, encoding);

        console.info('generate tpl module: ' + modulePath + ' at ' + (new Date().toLocaleString()));

    }

    var bufferCompile = S.buffer(compile);

    if (argv.watch) {
        fs.watch(tpl, bufferCompile);
        compile();
    } else {
        bufferCompile();
    }

});