"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const path_1 = __importDefault(require("path"));
const faker_1 = __importDefault(require("faker"));
const sleep = (time) => {
    return new Promise(resolve => setTimeout(resolve, time));
};
exports.default = (options) => {
    return async (req, res) => {
        const method = req.path.replace(/^\//, '');
        if (!method) {
            res.status(404).send({});
            return;
        }
        try {
            let { default: mock } = await Promise.resolve().then(() => __importStar(require(path_1.default.resolve(options.path, method))));
            if ('function' === typeof mock) {
                mock = await mock(req, res);
            }
            let delay = 0;
            if ('function' === typeof options.delay) {
                delay = options.delay(method);
            }
            else if (options.delay) {
                delay = options.delay;
            }
            if (delay) {
                await sleep(delay);
            }
            if (mock instanceof ArrayBuffer) {
                res.send(Buffer.from(mock));
            }
            else {
                const result = JSON.parse(faker_1.default.fake(JSON.stringify(mock, null, 4)));
                if ('status' in result && 'data' in result) {
                    res.json(result);
                }
                else {
                    res.json({ status: 0, msg: '', data: result });
                }
            }
        }
        catch (e) {
            res.status(500).send(e.message);
        }
    };
};
