"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 { getScreenParams, generateScreenID } = require("../../db/utils");
const { AccessController } = require("@devlego/backend-core/roles");
const { getAppDB } = require("@devlego/backend-core/context");
const { events } = require("@devlego/backend-core");
exports.fetch = (ctx) => __awaiter(void 0, void 0, void 0, function* () {
    const db = getAppDB();
    const screens = (yield db.allDocs(getScreenParams(null, {
        include_docs: true,
    }))).rows.map(element => element.doc);
    ctx.body = yield new AccessController().checkScreensAccess(screens, ctx.user.role._id);
});
exports.save = (ctx) => __awaiter(void 0, void 0, void 0, function* () {
    let screen = ctx.request.body;
    const db = getAppDB();
    let eventFn;
    if (!screen._id) {
        screen._id = generateScreenID();
        eventFn = events.screen.created;
    }
    const response = yield db.put(screen);
    if (eventFn) {
        yield eventFn(screen);
    }
    ctx.message = `Screen ${screen.name} saved.`;
    ctx.body = Object.assign(Object.assign({}, screen), { _id: response.id, _rev: response.rev });
});
exports.destroy = (ctx) => __awaiter(void 0, void 0, void 0, function* () {
    const db = getAppDB();
    const id = ctx.params.screenId;
    const screen = yield db.get(id);
    yield db.remove(id, ctx.params.screenRev);
    yield events.screen.deleted(screen);
    ctx.body = {
        message: "Screen deleted successfully",
    };
    ctx.status = 200;
});
