"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var common_1 = require("../common");
var Manifest_1 = require("./Manifest");
var util = require("./util");
function init(args) {
    var _this = this;
    var rootDir = args.rootDir, _a = args.manifestPath, manifestPath = _a === void 0 ? '/manifest' : _a, _b = args.resourcePath, resourcePath = _b === void 0 ? '/resource' : _b;
    var router = common_1.express.router();
    router.get(manifestPath, function (req, res) { return tslib_1.__awaiter(_this, void 0, void 0, function () {
        var timer, query, path, loadExtensions, loadFlag, done, error, manifest, _a, _b, _c;
        return tslib_1.__generator(this, function (_d) {
            switch (_d.label) {
                case 0:
                    timer = common_1.time.timer();
                    query = req.query;
                    path = query.path;
                    loadExtensions = [];
                    loadFlag = function () {
                        var flag = [];
                        for (var _i = 0; _i < arguments.length; _i++) {
                            flag[_i] = arguments[_i];
                        }
                        if (common_1.queryString.isFlag(flag, query)) {
                            loadExtensions = loadExtensions.concat(flag);
                        }
                    };
                    loadFlag('markdown', 'md');
                    loadFlag('json');
                    loadFlag('yaml', 'yml');
                    done = function (status, args) {
                        var payload = common_1.value.deleteUndefined({
                            status: status,
                            elapsed: timer.elapsed(),
                            error: args.error ? { message: args.error } : undefined,
                            manifest: args.manifest,
                        });
                        res.status(status).send(payload);
                    };
                    if (!path) {
                        error = "A '?path=<...>' was not passed in the URL's querystring.";
                        return [2, done(400, { error: error })];
                    }
                    manifest = new Manifest_1.Manifest({
                        rootDir: rootDir,
                        path: path,
                        urlPrefix: resourcePath,
                    });
                    _a = done;
                    _b = [200];
                    _c = {};
                    return [4, manifest.toObject({ loadExtensions: loadExtensions })];
                case 1: return [2, _a.apply(void 0, _b.concat([(_c.manifest = _d.sent(),
                            _c)]))];
            }
        });
    }); });
    var RESOURCE_ROUTE = common_1.fsPath.join(resourcePath.replace(/\/\*$/, ''), '*');
    router.get(RESOURCE_ROUTE, function (req, res) { return tslib_1.__awaiter(_this, void 0, void 0, function () {
        var path, file, exists, _a, query, data, ext, res_1, res_2, err_1, status_1, message;
        return tslib_1.__generator(this, function (_b) {
            switch (_b.label) {
                case 0:
                    _b.trys.push([0, 8, , 9]);
                    path = (req.params['0'] || '');
                    file = common_1.fsPath.join(rootDir, path);
                    if (!file) return [3, 2];
                    return [4, common_1.fs.pathExists(file)];
                case 1:
                    _a = _b.sent();
                    return [3, 3];
                case 2:
                    _a = false;
                    _b.label = 3;
                case 3:
                    exists = _a;
                    query = req.query;
                    data = void 0;
                    ext = common_1.fsPath.extname(path).toLowerCase();
                    if (!['.yml', '.yaml'].includes(ext)) return [3, 5];
                    return [4, util.parseYamlFile(file)];
                case 4:
                    res_1 = _b.sent();
                    if (res_1.error) {
                        throw new Error(res_1.error.message);
                    }
                    data = res_1.data;
                    _b.label = 5;
                case 5:
                    if (!(['.md', '.markdown'].includes(ext) &&
                        common_1.queryString.isFlag('parse', query))) return [3, 7];
                    return [4, util.parseMarkdownFile(file)];
                case 6:
                    res_2 = _b.sent();
                    if (res_2.error) {
                        throw new Error(res_2.error.message);
                    }
                    data = res_2.data;
                    _b.label = 7;
                case 7: return [2, file && exists
                        ? data
                            ? res.send(data)
                            : res.sendFile(file)
                        : res.status(404).send({
                            status: 404,
                            error: { message: 'Resource not found.', path: path },
                        })];
                case 8:
                    err_1 = _b.sent();
                    status_1 = 500;
                    message = "Failed to retrieve resource. " + err_1.message;
                    res.status(status_1).send({ status: status_1, error: { message: message } });
                    return [3, 9];
                case 9: return [2];
            }
        });
    }); });
    return router;
}
exports.init = init;
//# sourceMappingURL=router.js.map