"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 { ViewNames, generateMemoryViewID, getMemoryViewParams, DocumentTypes, SEPARATOR, } = require("../../../db/utils");
const env = require("../../../environment");
const { getAppDB } = require("@devlego/backend-core/context");
const viewBuilder = require("./viewBuilder");
exports.getView = (viewName) => __awaiter(void 0, void 0, void 0, function* () {
    const db = getAppDB();
    if (env.SELF_HOSTED) {
        const designDoc = yield db.get("_design/database");
        return designDoc.views[viewName];
    }
    else {
        // This is a table view, don't read the view from the DB
        if (viewName.startsWith(DocumentTypes.TABLE + SEPARATOR)) {
            return null;
        }
        const viewDoc = yield db.get(generateMemoryViewID(viewName));
        return viewDoc.view;
    }
});
exports.getViews = () => __awaiter(void 0, void 0, void 0, function* () {
    const db = getAppDB();
    const response = [];
    if (env.SELF_HOSTED) {
        const designDoc = yield db.get("_design/database");
        for (let name of Object.keys(designDoc.views)) {
            // Only return custom views, not built ins
            if (Object.values(ViewNames).indexOf(name) !== -1) {
                continue;
            }
            response.push(Object.assign({ name }, designDoc.views[name]));
        }
    }
    else {
        const views = (yield db.allDocs(getMemoryViewParams({
            include_docs: true,
        }))).rows.map(row => row.doc);
        for (let viewDoc of views) {
            response.push(Object.assign({ name: viewDoc.name }, viewDoc.view));
        }
    }
    return response;
});
exports.saveView = (originalName, viewName, viewTemplate) => __awaiter(void 0, void 0, void 0, function* () {
    const db = getAppDB();
    if (env.SELF_HOSTED) {
        const designDoc = yield db.get("_design/database");
        designDoc.views = Object.assign(Object.assign({}, designDoc.views), { [viewName]: viewTemplate });
        // view has been renamed
        if (originalName) {
            delete designDoc.views[originalName];
        }
        yield db.put(designDoc);
    }
    else {
        const id = generateMemoryViewID(viewName);
        const originalId = originalName ? generateMemoryViewID(originalName) : null;
        const viewDoc = {
            _id: id,
            view: viewTemplate,
            name: viewName,
            tableId: viewTemplate.meta.tableId,
        };
        try {
            const old = yield db.get(id);
            if (originalId) {
                const originalDoc = yield db.get(originalId);
                yield db.remove(originalDoc._id, originalDoc._rev);
            }
            if (old && old._rev) {
                viewDoc._rev = old._rev;
            }
        }
        catch (err) {
            // didn't exist, just skip
        }
        yield db.put(viewDoc);
    }
});
exports.deleteView = (viewName) => __awaiter(void 0, void 0, void 0, function* () {
    const db = getAppDB();
    if (env.SELF_HOSTED) {
        const designDoc = yield db.get("_design/database");
        const view = designDoc.views[viewName];
        delete designDoc.views[viewName];
        yield db.put(designDoc);
        return view;
    }
    else {
        const id = generateMemoryViewID(viewName);
        const viewDoc = yield db.get(id);
        yield db.remove(viewDoc._id, viewDoc._rev);
        return viewDoc.view;
    }
});
exports.migrateToInMemoryView = (db, viewName) => __awaiter(void 0, void 0, void 0, function* () {
    // delete the view initially
    const designDoc = yield db.get("_design/database");
    // run the view back through the view builder to update it
    const view = viewBuilder(designDoc.views[viewName].meta);
    delete designDoc.views[viewName];
    yield db.put(designDoc);
    yield exports.saveView(db, null, viewName, view);
});
exports.migrateToDesignView = (db, viewName) => __awaiter(void 0, void 0, void 0, function* () {
    let view = yield db.get(generateMemoryViewID(viewName));
    const designDoc = yield db.get("_design/database");
    designDoc.views[viewName] = viewBuilder(view.view.meta);
    yield db.put(designDoc);
    yield db.remove(view._id, view._rev);
});
exports.getFromDesignDoc = (db, viewName) => __awaiter(void 0, void 0, void 0, function* () {
    const designDoc = yield db.get("_design/database");
    let view = designDoc.views[viewName];
    if (view == null) {
        throw { status: 404, message: "Unable to get view" };
    }
    return view;
});
exports.getFromMemoryDoc = (db, viewName) => __awaiter(void 0, void 0, void 0, function* () {
    let view = yield db.get(generateMemoryViewID(viewName));
    if (view) {
        view = view.view;
    }
    else {
        throw { status: 404, message: "Unable to get view" };
    }
    return view;
});
