import UserMiddleware from "../Middleware/UserAuthorization";
import MonitorTemplateService from "../Services/MonitorTemplateService";
import Response from "../Utils/Response";
import BaseAPI from "./BaseAPI";
import CommonAPI from "./CommonAPI";
import MonitorTemplate from "../../Models/DatabaseModels/MonitorTemplate";
import BadDataException from "../../Types/Exception/BadDataException";
import ObjectID from "../../Types/ObjectID";
/**
 * Pull a `fields` whitelist out of the request body for a sync endpoint.
 * Returns undefined when the caller didn't ask to scope the sync — the
 * service treats that as "sync everything syncable".
 */
function readSyncFields(req) {
    var _a;
    const raw = (_a = req.body) === null || _a === void 0 ? void 0 : _a["fields"];
    if (raw === undefined || raw === null) {
        return undefined;
    }
    if (!Array.isArray(raw)) {
        throw new BadDataException("`fields` must be an array of strings");
    }
    for (const entry of raw) {
        if (typeof entry !== "string") {
            throw new BadDataException("`fields` must be an array of strings");
        }
    }
    return raw;
}
export default class MonitorTemplateAPI extends BaseAPI {
    constructor() {
        var _a, _b, _c, _d;
        super(MonitorTemplate, MonitorTemplateService);
        // Push the template's current configuration onto every linked monitor.
        this.router.post(`${(_a = new this.entityType()
            .getCrudApiPath()) === null || _a === void 0 ? void 0 : _a.toString()}/:monitorTemplateId/sync-to-linked-monitors`, UserMiddleware.getUserMiddleware, async (req, res, next) => {
            try {
                const monitorTemplateId = new ObjectID(req.params["monitorTemplateId"]);
                const props = await CommonAPI.getDatabaseCommonInteractionProps(req);
                const fields = readSyncFields(req);
                const result = await MonitorTemplateService.syncLinkedMonitors(Object.assign({ monitorTemplateId,
                    props }, (fields !== undefined ? { fields } : {})));
                return Response.sendJsonObjectResponse(req, res, Object.assign({}, result));
            }
            catch (e) {
                next(e);
            }
            return;
        });
        // Push the template's current configuration onto a single linked monitor.
        this.router.post(`${(_b = new this.entityType()
            .getCrudApiPath()) === null || _b === void 0 ? void 0 : _b.toString()}/:monitorTemplateId/sync-to-monitor/:monitorId`, UserMiddleware.getUserMiddleware, async (req, res, next) => {
            try {
                const monitorTemplateId = new ObjectID(req.params["monitorTemplateId"]);
                const monitorId = new ObjectID(req.params["monitorId"]);
                const props = await CommonAPI.getDatabaseCommonInteractionProps(req);
                const fields = readSyncFields(req);
                await MonitorTemplateService.syncToMonitor(Object.assign({ monitorTemplateId,
                    monitorId,
                    props }, (fields !== undefined ? { fields } : {})));
                return Response.sendEmptySuccessResponse(req, res);
            }
            catch (e) {
                next(e);
            }
            return;
        });
        // Link an existing monitor to this template.
        this.router.post(`${(_c = new this.entityType()
            .getCrudApiPath()) === null || _c === void 0 ? void 0 : _c.toString()}/:monitorTemplateId/link-monitor/:monitorId`, UserMiddleware.getUserMiddleware, async (req, res, next) => {
            try {
                const monitorTemplateId = new ObjectID(req.params["monitorTemplateId"]);
                const monitorId = new ObjectID(req.params["monitorId"]);
                const props = await CommonAPI.getDatabaseCommonInteractionProps(req);
                await MonitorTemplateService.linkMonitor({
                    monitorTemplateId,
                    monitorId,
                    props,
                });
                return Response.sendEmptySuccessResponse(req, res);
            }
            catch (e) {
                next(e);
            }
            return;
        });
        // Detach a monitor from this template.
        this.router.post(`${(_d = new this.entityType()
            .getCrudApiPath()) === null || _d === void 0 ? void 0 : _d.toString()}/:monitorTemplateId/unlink-monitor/:monitorId`, UserMiddleware.getUserMiddleware, async (req, res, next) => {
            try {
                const monitorTemplateId = new ObjectID(req.params["monitorTemplateId"]);
                const monitorId = new ObjectID(req.params["monitorId"]);
                const props = await CommonAPI.getDatabaseCommonInteractionProps(req);
                await MonitorTemplateService.unlinkMonitor({
                    monitorTemplateId,
                    monitorId,
                    props,
                });
                return Response.sendEmptySuccessResponse(req, res);
            }
            catch (e) {
                next(e);
            }
            return;
        });
    }
}
//# sourceMappingURL=MonitorTemplateAPI.js.map