"use strict";
/*************************************************************************
 *
 * Troven CONFIDENTIAL
 * __________________
 *
 *  (c) 2017-2020 Troven Pty Ltd
 *  All Rights Reserved.
 *
 * NOTICE:  All information contained herein is, and remains
 * the property of Troven Pty Ltd and its licensors,
 * if any.  The intellectual and technical concepts contained
 * herein are proprietary to Troven Pty Ltd
 * and its suppliers and may be covered by International and Regional Patents,
 * patents in process, and are protected by trade secret or copyright law.
 * Dissemination of this information or reproduction of this material
 * is strictly forbidden unless prior written permission is obtained
 * from Troven Pty Ltd.
 */
Object.defineProperty(exports, "__esModule", { value: true });
const api_service_core_1 = require("api-service-core");
const _ = require("lodash");
const fs = require("fs");
const showdown = require("showdown"); // https://github.com/showdownjs/showdown
// import * as handlebars from 'express-handlebars'
const fm = require("front-matter");
const assert = require("assert");
class Markdown {
    constructor() {
        this.name = "api.markdown";
        this.title = "HTML using Markdown";
    }
    fn(operation, _options) {
        let options = _.extend({ render: {}, template: "markdown.hbs" }, _options);
        let renderer = operation.context.plugins.get("render");
        assert(renderer, "render plugin not installed");
        let feature = _options.feature || {};
        let context = operation.context;
        // same as common/middleware/render
        let default_page_context = _.extend({
            markdown: "", layout: "default",
            brand: _.extend({}, options.render.brand, feature.brand),
            i18n: _.extend({}, options.render.i18n, feature.i18n),
            pkg: { name: context.pkg.name, version: context.pkg.version }
        }, renderer.render_options);
        showdown.setFlavor('github');
        showdown.extension('bootstrap-tables', {
            type: 'output',
            filter: (html) => {
                const regex = /<table>/g;
                return html.replace(regex, '<table class="table table-bordered">');
            },
        });
        // see https://github.com/showdownjs/showdown/wiki/Showdown-options
        let showdown_options = _.extend({ tables: true, simplifiedAutoLink: true, ghCodeBlocks: true, strikethrough: true,
            tasklists: true, simpleLineBreaks: true, encodeEmails: true, parseImgDimensions: true, excludeTrailingPunctuationFromURLs: true }, { extensions: ["bootstrap-tables"] }, options.showdown);
        let markdown = new showdown.Converter(showdown_options);
        let folder = options.folder || ".";
        let feature_apis = _.extend({}, renderer.render_options.apis, feature.apis);
        return function (req, res, _next) {
            let page = req.params[0];
            if (!page || page.endsWith("/")) {
                page = page + "index.md";
            }
            let file = folder + "/" + page;
            try {
                let text = fs.readFileSync(file, "UTF-8");
                let matter = fm(text);
                let page_context = _.extend({}, default_page_context, matter.attributes);
                let api_params = _.extend({}, feature.request, page_context);
                let jwt_token = feature.reuseJWT ? req.header("authorization") : "";
                api_service_core_1.APIs.requests(context, feature_apis, api_params, jwt_token).then(results => {
                    let render_context = _.extend(page_context, results);
                    renderer.hbs.getPartials().then((partials) => {
                        // console.log("page_context: %o --> %o", page_context, partials);
                        let parsed = renderer.hbs._compileTemplate(matter.body, { partials: partials })(render_context);
                        // console.log("parsed: %o", parsed);
                        let html = markdown.makeHtml(parsed);
                        res.set('Content-Type', 'text/html');
                        page_context.markdown = html;
                        res.render(options.template, render_context);
                    }).catch(err => {
                        context.error({ code: "plugin:markdown:partials:failed", message: err.message, path: req.path, page: page, file: file, params: req.params });
                        res.status(500);
                        res.send({ code: "plugin:markdown:partials:failed", message: err.message, path: req.path, file: file, params: req.params });
                    });
                });
            }
            catch (err) {
                console.error(err);
                context.error({ code: "plugin:markdown:failed", message: err.message, path: req.path, page: page, file: file, params: req.params });
                res.status(500);
                res.send({ code: "plugin:markdown:failed", message: err.message, path: req.path, file: file, params: req.params });
            }
        };
    }
}
exports.default = Markdown;
;
//# sourceMappingURL=Markdown.js.map