"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());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Dwn = void 0;
var tenant_gate_js_1 = require("./core/tenant-gate.js");
var data_store_level_js_1 = require("./store/data-store-level.js");
var did_resolver_js_1 = require("./did/did-resolver.js");
var event_log_level_js_1 = require("./event-log/event-log-level.js");
var events_get_js_1 = require("./interfaces/events/handlers/events-get.js");
var message_reply_js_1 = require("./core/message-reply.js");
var messages_get_js_1 = require("./interfaces/messages/handlers/messages-get.js");
var message_store_level_js_1 = require("./store/message-store-level.js");
var protocols_configure_js_1 = require("./interfaces/protocols/handlers/protocols-configure.js");
var protocols_query_js_1 = require("./interfaces/protocols/handlers/protocols-query.js");
var records_delete_js_1 = require("./interfaces/records/handlers/records-delete.js");
var records_query_js_1 = require("./interfaces/records/handlers/records-query.js");
var records_read_js_1 = require("./interfaces/records/handlers/records-read.js");
var records_write_js_1 = require("./interfaces/records/handlers/records-write.js");
var message_js_1 = require("./core/message.js");
var Dwn = /** @class */ (function () {
    function Dwn(config) {
        var _a;
        this.didResolver = config.didResolver;
        this.messageStore = config.messageStore;
        this.dataStore = config.dataStore;
        this.eventLog = config.eventLog;
        this.tenantGate = config.tenantGate;
        this.methodHandlers = (_a = {},
            _a[message_js_1.DwnInterfaceName.Events + message_js_1.DwnMethodName.Get] = new events_get_js_1.EventsGetHandler(this.didResolver, this.eventLog),
            _a[message_js_1.DwnInterfaceName.Messages + message_js_1.DwnMethodName.Get] = new messages_get_js_1.MessagesGetHandler(this.didResolver, this.messageStore, this.dataStore),
            _a[message_js_1.DwnInterfaceName.Protocols + message_js_1.DwnMethodName.Configure] = new protocols_configure_js_1.ProtocolsConfigureHandler(this.didResolver, this.messageStore, this.dataStore, this.eventLog),
            _a[message_js_1.DwnInterfaceName.Protocols + message_js_1.DwnMethodName.Query] = new protocols_query_js_1.ProtocolsQueryHandler(this.didResolver, this.messageStore, this.dataStore),
            _a[message_js_1.DwnInterfaceName.Records + message_js_1.DwnMethodName.Delete] = new records_delete_js_1.RecordsDeleteHandler(this.didResolver, this.messageStore, this.dataStore, this.eventLog),
            _a[message_js_1.DwnInterfaceName.Records + message_js_1.DwnMethodName.Query] = new records_query_js_1.RecordsQueryHandler(this.didResolver, this.messageStore, this.dataStore),
            _a[message_js_1.DwnInterfaceName.Records + message_js_1.DwnMethodName.Read] = new records_read_js_1.RecordsReadHandler(this.didResolver, this.messageStore, this.dataStore),
            _a[message_js_1.DwnInterfaceName.Records + message_js_1.DwnMethodName.Write] = new records_write_js_1.RecordsWriteHandler(this.didResolver, this.messageStore, this.dataStore, this.eventLog),
            _a);
    }
    /**
     * Creates an instance of the DWN.
     */
    Dwn.create = function (config) {
        var _a, _b, _c, _d, _e;
        return __awaiter(this, void 0, void 0, function () {
            var dwn;
            return __generator(this, function (_f) {
                switch (_f.label) {
                    case 0:
                        config !== null && config !== void 0 ? config : (config = {});
                        (_a = config.didResolver) !== null && _a !== void 0 ? _a : (config.didResolver = new did_resolver_js_1.DidResolver());
                        (_b = config.tenantGate) !== null && _b !== void 0 ? _b : (config.tenantGate = new tenant_gate_js_1.AllowAllTenantGate());
                        (_c = config.messageStore) !== null && _c !== void 0 ? _c : (config.messageStore = new message_store_level_js_1.MessageStoreLevel());
                        (_d = config.dataStore) !== null && _d !== void 0 ? _d : (config.dataStore = new data_store_level_js_1.DataStoreLevel());
                        (_e = config.eventLog) !== null && _e !== void 0 ? _e : (config.eventLog = new event_log_level_js_1.EventLogLevel());
                        dwn = new Dwn(config);
                        return [4 /*yield*/, dwn.open()];
                    case 1:
                        _f.sent();
                        return [2 /*return*/, dwn];
                }
            });
        });
    };
    Dwn.prototype.open = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.messageStore.open()];
                    case 1:
                        _a.sent();
                        return [4 /*yield*/, this.dataStore.open()];
                    case 2:
                        _a.sent();
                        return [4 /*yield*/, this.eventLog.open()];
                    case 3:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    Dwn.prototype.close = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                this.messageStore.close();
                this.dataStore.close();
                this.eventLog.close();
                return [2 /*return*/];
            });
        });
    };
    /**
     * Processes the given DWN message and returns with a reply.
     * @param tenant The tenant DID to route the given message to.
     */
    Dwn.prototype.processMessage = function (tenant, rawMessage, dataStream) {
        return __awaiter(this, void 0, void 0, function () {
            var errorMessageReply, handlerKey, methodHandlerReply;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.preprocessingChecks(tenant, rawMessage)];
                    case 1:
                        errorMessageReply = _a.sent();
                        if (errorMessageReply !== undefined) {
                            return [2 /*return*/, errorMessageReply];
                        }
                        handlerKey = rawMessage.descriptor.interface + rawMessage.descriptor.method;
                        return [4 /*yield*/, this.methodHandlers[handlerKey].handle({
                                tenant: tenant,
                                message: rawMessage,
                                dataStream: dataStream
                            })];
                    case 2:
                        methodHandlerReply = _a.sent();
                        return [2 /*return*/, methodHandlerReply];
                }
            });
        });
    };
    /**
     * Handles a `RecordsQuery` message.
     */
    Dwn.prototype.handleRecordsQuery = function (tenant, message) {
        return __awaiter(this, void 0, void 0, function () {
            var errorMessageReply, handler;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.preprocessingChecks(tenant, message, message_js_1.DwnInterfaceName.Records, message_js_1.DwnMethodName.Query)];
                    case 1:
                        errorMessageReply = _a.sent();
                        if (errorMessageReply !== undefined) {
                            return [2 /*return*/, errorMessageReply];
                        }
                        handler = new records_query_js_1.RecordsQueryHandler(this.didResolver, this.messageStore, this.dataStore);
                        return [2 /*return*/, handler.handle({ tenant: tenant, message: message })];
                }
            });
        });
    };
    /**
     * Handles a `RecordsRead` message.
     */
    Dwn.prototype.handleRecordsRead = function (tenant, message) {
        return __awaiter(this, void 0, void 0, function () {
            var errorMessageReply, handler;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.preprocessingChecks(tenant, message, message_js_1.DwnInterfaceName.Records, message_js_1.DwnMethodName.Read)];
                    case 1:
                        errorMessageReply = _a.sent();
                        if (errorMessageReply !== undefined) {
                            return [2 /*return*/, errorMessageReply];
                        }
                        handler = new records_read_js_1.RecordsReadHandler(this.didResolver, this.messageStore, this.dataStore);
                        return [2 /*return*/, handler.handle({ tenant: tenant, message: message })];
                }
            });
        });
    };
    /**
     * Handles a `MessagesGet` message.
     */
    Dwn.prototype.handleMessagesGet = function (tenant, message) {
        return __awaiter(this, void 0, void 0, function () {
            var errorMessageReply, handler;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.preprocessingChecks(tenant, message, message_js_1.DwnInterfaceName.Messages, message_js_1.DwnMethodName.Get)];
                    case 1:
                        errorMessageReply = _a.sent();
                        if (errorMessageReply !== undefined) {
                            return [2 /*return*/, errorMessageReply];
                        }
                        handler = new messages_get_js_1.MessagesGetHandler(this.didResolver, this.messageStore, this.dataStore);
                        return [2 /*return*/, handler.handle({ tenant: tenant, message: message })];
                }
            });
        });
    };
    /**
     * Privileged method for writing a pruned initial `RecordsWrite` to a DWN without needing to supply associated data.
     */
    Dwn.prototype.synchronizePrunedInitialRecordsWrite = function (tenant, message) {
        return __awaiter(this, void 0, void 0, function () {
            var errorMessageReply, options, handler, methodHandlerReply;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.preprocessingChecks(tenant, message, message_js_1.DwnInterfaceName.Records, message_js_1.DwnMethodName.Write)];
                    case 1:
                        errorMessageReply = _a.sent();
                        if (errorMessageReply !== undefined) {
                            return [2 /*return*/, errorMessageReply];
                        }
                        options = {
                            skipDataStorage: true,
                        };
                        handler = new records_write_js_1.RecordsWriteHandler(this.didResolver, this.messageStore, this.dataStore, this.eventLog);
                        return [4 /*yield*/, handler.handle({ tenant: tenant, message: message, options: options })];
                    case 2:
                        methodHandlerReply = _a.sent();
                        return [2 /*return*/, methodHandlerReply];
                }
            });
        });
    };
    /**
     * Common checks for handlers.
     */
    Dwn.prototype.preprocessingChecks = function (tenant, rawMessage, expectedInterface, expectedMethod) {
        var _a, _b;
        return __awaiter(this, void 0, void 0, function () {
            var isTenant, dwnInterface, dwnMethod;
            return __generator(this, function (_c) {
                switch (_c.label) {
                    case 0: return [4 /*yield*/, this.tenantGate.isTenant(tenant)];
                    case 1:
                        isTenant = _c.sent();
                        if (!isTenant) {
                            return [2 /*return*/, new message_reply_js_1.MessageReply({
                                    status: { code: 401, detail: "".concat(tenant, " is not a tenant") }
                                })];
                        }
                        dwnInterface = (_a = rawMessage === null || rawMessage === void 0 ? void 0 : rawMessage.descriptor) === null || _a === void 0 ? void 0 : _a.interface;
                        dwnMethod = (_b = rawMessage === null || rawMessage === void 0 ? void 0 : rawMessage.descriptor) === null || _b === void 0 ? void 0 : _b.method;
                        if (dwnInterface === undefined || dwnMethod === undefined) {
                            return [2 /*return*/, new message_reply_js_1.MessageReply({
                                    status: { code: 400, detail: "Both interface and method must be present, interface: ".concat(dwnInterface, ", method: ").concat(dwnMethod) }
                                })];
                        }
                        if (expectedInterface !== undefined && expectedInterface !== dwnInterface) {
                            return [2 /*return*/, new message_reply_js_1.MessageReply({
                                    status: { code: 400, detail: "Expected interface ".concat(expectedInterface, ", received ").concat(dwnInterface) }
                                })];
                        }
                        if (expectedMethod !== undefined && expectedMethod !== dwnMethod) {
                            return [2 /*return*/, new message_reply_js_1.MessageReply({
                                    status: { code: 400, detail: "Expected method ".concat(expectedInterface).concat(expectedMethod, ", received ").concat(dwnInterface).concat(dwnMethod) }
                                })];
                        }
                        // validate message structure
                        try {
                            // consider to push this down to individual handlers
                            message_js_1.Message.validateJsonSchema(rawMessage);
                        }
                        catch (error) {
                            return [2 /*return*/, message_reply_js_1.MessageReply.fromError(error, 400)];
                        }
                        return [2 /*return*/, undefined];
                }
            });
        });
    };
    return Dwn;
}());
exports.Dwn = Dwn;
;
//# sourceMappingURL=dwn.js.map