let fs = require('fs')
let Mustache = require('mustache')
const crypto = require('crypto')
import {FileUtils} from './fileutils'

interface TemplateCallbackType {
    (rendered: string[]): void
}

export function loadTemplate(filename: string, objs: object[], cb: TemplateCallbackType) {
    let fu = new FileUtils();
    let path = fu.getPathToView(filename);
    fs.readFile(path, 'utf8', (err, contents) => {
        if (err) throw err;
        let results: string[] = []
        for (let i = 0, l = objs.length; i < l; i++) {
            let obj = objs[i]
            let rendered = Mustache.render(contents, obj)
            results.push(rendered)
        }
        cb(results)
    })
}

export function loadTemplateSingle(filename: string, obj: object, cb: (content: string, id: string) => void) {
    let fu = new FileUtils();
    let path = fu.getPathToView(filename);
    fs.readFile(path, 'utf8', (err, contents) => {
        if (err) throw err;
        obj['id'] = createId(filename);
        let rendered = Mustache.render(contents, obj)
        cb(rendered, obj['id'])
    })
}

function createId(fileName: String){
    return crypto.createHash('md5').update(fileName).digest('hex');
}

module.exports = {loadTemplate, loadTemplateSingle}

