import {FileUtils} from './fileutils';
import {CardModel} from "./viewFactory";

let fs = require('fs');
let Mustache = require('mustache');
const crypto = require('crypto');
let path = require('path');

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

const templateCache = {};

export function cacheTemplates() {
    let basePath = path.join(FileUtils.getPathToAssets(), "views");
    fs.readdirSync(basePath)
        .forEach((file) => {
            templateCache[file] = fs.readFileSync(path.join(basePath.toString(), file)).toString();
        });
}

export function loadTemplate(filename: string, objs: object[], cb: TemplateCallbackType) {
    let contents = templateCache[filename];
    if (!contents) throw new Error("No such template: " + filename);
    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, cardModel: CardModel, cb: (content: string, id: string) => void) {
    let contents = templateCache[filename];
    if (!contents) throw new Error("No such template: " + filename);
    cardModel['id'] = createId(cardModel.resourcePath);
    let rendered = Mustache.render(contents, cardModel);
    cb(rendered, cardModel['id']);
}

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

module.exports = {loadTemplate, loadTemplateSingle}

cacheTemplates()