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, obj: object, cb: TemplateCallbackType): string {
    let contents = templateCache[filename];
    if (!contents) throw new Error("No such template: " + filename);
    let rendered = Mustache.render(contents, obj)
    if (null !== cb) {
        cb(rendered)
    }
    return rendered;
}

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.title + cardModel.resourcePath);
    let rendered = Mustache.render(contents, cardModel);
    cb(rendered, cardModel['id']);
}

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

export function readHTML(fileName: string): string{
    let baseFilePath = FileUtils.getPathToPage(fileName);
    return fs.readFileSync(baseFilePath, "utf8").toString();
}

module.exports = {loadTemplate, loadTemplateSingle, readHTML}

cacheTemplates()