"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
const { EMPTY_LAYOUT } = require("../../constants/layouts");
const { generateLayoutID, getScreenParams } = require("../../db/utils");
const { getAppDB } = require("@devlego/backend-core/context");
const { events } = require("@devlego/backend-core");
exports.save = function (ctx) {
    return __awaiter(this, void 0, void 0, function* () {
        const db = getAppDB();
        let layout = ctx.request.body;
        if (!layout.props) {
            layout = Object.assign(Object.assign({}, EMPTY_LAYOUT), layout);
            layout.props._instanceName = layout.name;
        }
        layout._id = layout._id || generateLayoutID();
        const response = yield db.put(layout);
        yield events.layout.created(layout);
        layout._rev = response.rev;
        ctx.body = layout;
        ctx.status = 200;
    });
};
exports.destroy = function (ctx) {
    return __awaiter(this, void 0, void 0, function* () {
        const db = getAppDB();
        const layoutId = ctx.params.layoutId, layoutRev = ctx.params.layoutRev;
        const layoutsUsedByScreens = (yield db.allDocs(getScreenParams(null, {
            include_docs: true,
        }))).rows.map(element => element.doc.layoutId);
        if (layoutsUsedByScreens.includes(layoutId)) {
            ctx.throw(400, "Cannot delete a layout that's being used by a screen");
        }
        yield db.remove(layoutId, layoutRev);
        yield events.layout.deleted(layoutId);
        ctx.body = { message: "Layout deleted successfully" };
        ctx.status = 200;
    });
};
