var fs = require( 'fs' ); // 用于处理本地文件
var path = require( 'path' ); // 目录的处理API
var Smarty = require( 'sqp/smarty.js' );
var JsonFile = require( 'sqp/jsonfile' );

var conf = require( '../config/web.config.json' );
var tplext = conf.tplext;

exports.parse = function( realPath ) {

    if ( !conf.parse_smarty ) {
        return "";
    }

    var fileInfo = path.parse( realPath );
    var dirname = fileInfo.dir;
    var basename = fileInfo.name;
    var extname = fileInfo.ext.slice( 1 );

    var istpl = false;

    for ( var i = 0; i < tplext.length; i++ ) {
        if ( extname === tplext[ i ] ) {
            istpl = true;
        }
    }

    if ( !istpl ) {
        return "";
    }
    var jsonfile = path.resolve( dirname, "./" + basename + ".json" );

    //console.log( jsonfile );

    var exists = fs.existsSync( jsonfile );
    if ( !exists ) {
        return "";
    } else {
        var tplText = fs.readFileSync( realPath, {
            encoding: 'utf-8'
        } );

        Smarty.prototype.left_delimiter = conf.left_delimiter;
        Smarty.prototype.right_delimiter = conf.right_delimiter;

        var compiled = new Smarty( tplText );
        var jsondata = JsonFile.readFileSync( jsonfile, {
            encoding: 'utf-8'
        } );
        //console.log( jsondata );
        var res = compiled.fetch( jsondata );
        //console.log( res );
        return res;
    }
};