"use strict";
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
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 };
    }
};
var __rest = (this && this.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
};
var __values = (this && this.__values) || function(o) {
    var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
    if (m) return m.call(o);
    if (o && typeof o.length === "number") return {
        next: function () {
            if (o && i >= o.length) o = void 0;
            return { value: o && o[i++], done: !o };
        }
    };
    throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
var __read = (this && this.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.RecordsQueryHandler = void 0;
var auth_js_1 = require("../../../core/auth.js");
var string_js_1 = require("../../../utils/string.js");
var message_reply_js_1 = require("../../../core/message-reply.js");
var storage_controller_js_1 = require("../../../store/storage-controller.js");
var records_query_js_1 = require("../messages/records-query.js");
var message_js_1 = require("../../../core/message.js");
var RecordsQueryHandler = /** @class */ (function () {
    function RecordsQueryHandler(didResolver, messageStore, dataStore) {
        this.didResolver = didResolver;
        this.messageStore = messageStore;
        this.dataStore = dataStore;
    }
    RecordsQueryHandler.prototype.handle = function (_a) {
        var tenant = _a.tenant, message = _a.message;
        return __awaiter(this, void 0, void 0, function () {
            var recordsQuery, e_1, e_2, records, entries, records_1, records_1_1, record, _1, objectWithRemainingProperties;
            var e_3, _b;
            return __generator(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        _c.trys.push([0, 2, , 3]);
                        return [4 /*yield*/, records_query_js_1.RecordsQuery.parse(message)];
                    case 1:
                        recordsQuery = _c.sent();
                        return [3 /*break*/, 3];
                    case 2:
                        e_1 = _c.sent();
                        return [2 /*return*/, message_reply_js_1.MessageReply.fromError(e_1, 400)];
                    case 3:
                        _c.trys.push([3, 6, , 7]);
                        return [4 /*yield*/, (0, auth_js_1.authenticate)(message.authorization, this.didResolver)];
                    case 4:
                        _c.sent();
                        return [4 /*yield*/, recordsQuery.authorize(tenant)];
                    case 5:
                        _c.sent();
                        return [3 /*break*/, 7];
                    case 6:
                        e_2 = _c.sent();
                        return [2 /*return*/, message_reply_js_1.MessageReply.fromError(e_2, 401)];
                    case 7:
                        if (!(recordsQuery.author === tenant)) return [3 /*break*/, 9];
                        return [4 /*yield*/, this.fetchRecordsAsOwner(tenant, recordsQuery)];
                    case 8:
                        records = _c.sent();
                        return [3 /*break*/, 11];
                    case 9: return [4 /*yield*/, this.fetchRecordsAsNonOwner(tenant, recordsQuery)];
                    case 10:
                        records = _c.sent();
                        _c.label = 11;
                    case 11:
                        if (!recordsQuery.message.descriptor.dateSort) return [3 /*break*/, 13];
                        return [4 /*yield*/, sortRecords(records, recordsQuery.message.descriptor.dateSort)];
                    case 12:
                        records = _c.sent();
                        _c.label = 13;
                    case 13:
                        entries = [];
                        try {
                            for (records_1 = __values(records), records_1_1 = records_1.next(); !records_1_1.done; records_1_1 = records_1.next()) {
                                record = records_1_1.value;
                                _1 = record.authorization, objectWithRemainingProperties = __rest(record, ["authorization"]);
                                entries.push(objectWithRemainingProperties);
                            }
                        }
                        catch (e_3_1) { e_3 = { error: e_3_1 }; }
                        finally {
                            try {
                                if (records_1_1 && !records_1_1.done && (_b = records_1.return)) _b.call(records_1);
                            }
                            finally { if (e_3) throw e_3.error; }
                        }
                        return [2 /*return*/, {
                                status: { code: 200, detail: 'OK' },
                                entries: entries
                            }];
                }
            });
        });
    };
    /**
     * Fetches the records as the owner of the DWN with no additional filtering.
     */
    RecordsQueryHandler.prototype.fetchRecordsAsOwner = function (tenant, recordsQuery) {
        return __awaiter(this, void 0, void 0, function () {
            var filter, records;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        filter = __assign(__assign({}, records_query_js_1.RecordsQuery.convertFilter(recordsQuery.message.descriptor.filter)), { interface: message_js_1.DwnInterfaceName.Records, method: message_js_1.DwnMethodName.Write, isLatestBaseState: true });
                        return [4 /*yield*/, storage_controller_js_1.StorageController.query(this.messageStore, this.dataStore, tenant, filter)];
                    case 1:
                        records = _a.sent();
                        return [2 /*return*/, records];
                }
            });
        });
    };
    /**
     * Fetches the records as a non-owner, return only:
     * 1. published records; and
     * 2. unpublished records intended for the query author (where `recipient` is the query author)
     */
    RecordsQueryHandler.prototype.fetchRecordsAsNonOwner = function (tenant, recordsQuery) {
        return __awaiter(this, void 0, void 0, function () {
            var publishedRecords, unpublishedRecordsForQueryAuthor, unpublishedRecordsByAuthor, records;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.fetchPublishedRecords(tenant, recordsQuery)];
                    case 1:
                        publishedRecords = _a.sent();
                        return [4 /*yield*/, this.fetchUnpublishedRecordsForQueryAuthor(tenant, recordsQuery)];
                    case 2:
                        unpublishedRecordsForQueryAuthor = _a.sent();
                        return [4 /*yield*/, this.fetchUnpublishedRecordsByAuthor(tenant, recordsQuery)];
                    case 3:
                        unpublishedRecordsByAuthor = _a.sent();
                        records = __spreadArray(__spreadArray(__spreadArray([], __read(publishedRecords), false), __read(unpublishedRecordsForQueryAuthor), false), __read(unpublishedRecordsByAuthor), false);
                        return [2 /*return*/, records];
                }
            });
        });
    };
    /**
     * Fetches only published records.
     */
    RecordsQueryHandler.prototype.fetchPublishedRecords = function (tenant, recordsQuery) {
        return __awaiter(this, void 0, void 0, function () {
            var filter, publishedRecords;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        filter = __assign(__assign({}, records_query_js_1.RecordsQuery.convertFilter(recordsQuery.message.descriptor.filter)), { interface: message_js_1.DwnInterfaceName.Records, method: message_js_1.DwnMethodName.Write, published: true, isLatestBaseState: true });
                        return [4 /*yield*/, storage_controller_js_1.StorageController.query(this.messageStore, this.dataStore, tenant, filter)];
                    case 1:
                        publishedRecords = _a.sent();
                        return [2 /*return*/, publishedRecords];
                }
            });
        });
    };
    /**
     * Fetches only unpublished records that are intended for the query author (where `recipient` is the author).
     */
    RecordsQueryHandler.prototype.fetchUnpublishedRecordsForQueryAuthor = function (tenant, recordsQuery) {
        return __awaiter(this, void 0, void 0, function () {
            var filter, unpublishedRecordsForQueryAuthor;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        filter = __assign(__assign({}, records_query_js_1.RecordsQuery.convertFilter(recordsQuery.message.descriptor.filter)), { interface: message_js_1.DwnInterfaceName.Records, method: message_js_1.DwnMethodName.Write, recipient: recordsQuery.author, isLatestBaseState: true, published: false });
                        return [4 /*yield*/, storage_controller_js_1.StorageController.query(this.messageStore, this.dataStore, tenant, filter)];
                    case 1:
                        unpublishedRecordsForQueryAuthor = _a.sent();
                        return [2 /*return*/, unpublishedRecordsForQueryAuthor];
                }
            });
        });
    };
    /**
     * Fetches only unpublished records where the author is the same as the query author.
     */
    RecordsQueryHandler.prototype.fetchUnpublishedRecordsByAuthor = function (tenant, recordsQuery) {
        return __awaiter(this, void 0, void 0, function () {
            var filter, unpublishedRecordsForQueryAuthor;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        filter = __assign(__assign({}, records_query_js_1.RecordsQuery.convertFilter(recordsQuery.message.descriptor.filter)), { author: recordsQuery.author, interface: message_js_1.DwnInterfaceName.Records, method: message_js_1.DwnMethodName.Write, isLatestBaseState: true, published: false });
                        return [4 /*yield*/, storage_controller_js_1.StorageController.query(this.messageStore, this.dataStore, tenant, filter)];
                    case 1:
                        unpublishedRecordsForQueryAuthor = _a.sent();
                        return [2 /*return*/, unpublishedRecordsForQueryAuthor];
                }
            });
        });
    };
    return RecordsQueryHandler;
}());
exports.RecordsQueryHandler = RecordsQueryHandler;
/**
 * Sorts the given records. There are 4 options for dateSort:
 * 1. createdAscending - Sort in ascending order based on when the message was created
 * 2. createdDescending - Sort in descending order based on when the message was created
 * 3. publishedAscending - If the message is published, sort in asc based on publish date
 * 4. publishedDescending - If the message is published, sort in desc based on publish date
 *
 * If sorting is based on date published, records that are not published are filtered out.
 * @param messages - Messages to be sorted if dateSort is present
 * @param dateSort - Sorting scheme
 * @returns Sorted Messages
 */
function sortRecords(messages, dateSort) {
    return __awaiter(this, void 0, void 0, function () {
        return __generator(this, function (_a) {
            switch (dateSort) {
                case records_query_js_1.DateSort.CreatedAscending:
                    return [2 /*return*/, messages.sort(function (a, b) { return (0, string_js_1.lexicographicalCompare)(a.descriptor.dateCreated, b.descriptor.dateCreated); })];
                case records_query_js_1.DateSort.CreatedDescending:
                    return [2 /*return*/, messages.sort(function (a, b) { return (0, string_js_1.lexicographicalCompare)(b.descriptor.dateCreated, a.descriptor.dateCreated); })];
                case records_query_js_1.DateSort.PublishedAscending:
                    return [2 /*return*/, messages
                            .filter(function (m) { return m.descriptor.published; })
                            .sort(function (a, b) { return (0, string_js_1.lexicographicalCompare)(a.descriptor.datePublished, b.descriptor.datePublished); })];
                case records_query_js_1.DateSort.PublishedDescending:
                    return [2 /*return*/, messages
                            .filter(function (m) { return m.descriptor.published; })
                            .sort(function (a, b) { return (0, string_js_1.lexicographicalCompare)(b.descriptor.datePublished, a.descriptor.datePublished); })];
            }
            return [2 /*return*/];
        });
    });
}
//# sourceMappingURL=records-query.js.map