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 __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;
};
import { Convert } from '@enbox/common';
import { AgentPermissionsApi, DwnInterface, DwnPermissionRequest } from '@enbox/agent';
import { PermissionGrant } from './permission-grant.js';
/**
 * The `PermissionRequest` class encapsulates a permissions protocol `request` record, providing a more
 * developer-friendly interface for working with Decentralized Web Node (DWN) records.
 *
 * Methods are provided to grant the request and manage the request's lifecycle, including writing to remote DWNs.
 *
 * @beta
 */
export class PermissionRequest {
    constructor({ api, connectedDid, message, request }) {
        this._permissions = api;
        this._connectedDid = connectedDid;
        // Store the parsed request object.
        this._request = request;
        // Store the message that represents the grant.
        this._message = message;
    }
    /** parses the request given an agent, connectedDid and data encoded records write message  */
    static parse({ connectedDid, agent, message }) {
        const request = DwnPermissionRequest.parse(message);
        const api = new AgentPermissionsApi({ agent });
        return new PermissionRequest({ api, connectedDid, message, request });
    }
    /** The agent to use for this instantiation of the request */
    get agent() {
        return this._permissions.agent;
    }
    /** The request's ID, which is also the underlying record's ID  */
    get id() {
        return this._request.id;
    }
    /** The DID that is requesting a permission */
    get requester() {
        return this._request.requester;
    }
    /** (optional) Description of the permission request */
    get description() {
        return this._request.description;
    }
    /** Whether or not the permission request can be used to impersonate the grantor */
    get delegated() {
        return this._request.delegated;
    }
    /** The permission scope under which the requested grant would be valid */
    get scope() {
        return this._request.scope;
    }
    /** The conditions under which the requested grant would be valid */
    get conditions() {
        return this._request.conditions;
    }
    /** The `RecordsWrite` DWN message with encoded data that was used to instantiate this request */
    get rawMessage() {
        return this._message;
    }
    /**
     * Send the current permission request to a remote DWN by specifying their DID
     * If no DID is specified, the target is assumed to be the owner (connectedDID).
     *
     * @param target - the optional DID to send the permission request to, if none is set it is sent to the connectedDid
     * @returns the status of the send permission request
     *
     * @beta
     */
    send(target) {
        return __awaiter(this, void 0, void 0, function* () {
            target !== null && target !== void 0 ? target : (target = this._connectedDid);
            const _a = this._message, { encodedData } = _a, rawMessage = __rest(_a, ["encodedData"]);
            const dataStream = new Blob([Convert.base64Url(encodedData).toUint8Array()]);
            const sendRequestOptions = {
                messageType: DwnInterface.RecordsWrite,
                author: this._connectedDid,
                target: target,
                dataStream,
                rawMessage,
            };
            // Send the current/latest state to the target.
            const { reply } = yield this.agent.sendDwnRequest(sendRequestOptions);
            return reply;
        });
    }
    /**
     * Stores the current permission request to the owner's DWN.
     *
     * @param importGrant - if true, the permission request will signed by the owner before storing it to the owner's DWN. Defaults to false.
     * @returns the status of the store request
     *
     * @beta
     */
    store() {
        return __awaiter(this, void 0, void 0, function* () {
            const _a = this.rawMessage, { encodedData } = _a, rawMessage = __rest(_a, ["encodedData"]);
            const dataStream = new Blob([Convert.base64Url(encodedData).toUint8Array()]);
            const { reply, message } = yield this.agent.processDwnRequest({
                author: this._connectedDid,
                target: this._connectedDid,
                messageType: DwnInterface.RecordsWrite,
                rawMessage,
                dataStream,
            });
            this._message = Object.assign(Object.assign({}, message), { encodedData: encodedData });
            return { status: reply.status };
        });
    }
    /**
     * Grants the permission request to the requester.
     *
     * @param dateExpires - the date when the permission grant will expire.
     * @param store - if true, the permission grant will be stored in the owner's DWN. Defaults to true.
     * @returns {PermissionGrant} the granted permission.
     *
     * @beta
     */
    grant(dateExpires_1) {
        return __awaiter(this, arguments, void 0, function* (dateExpires, store = true) {
            const { message } = yield this._permissions.createGrant({
                requestId: this.id,
                grantedTo: this.requester,
                scope: this.scope,
                delegated: this.delegated,
                author: this._connectedDid,
                store,
                dateExpires,
            });
            return PermissionGrant.parse({
                connectedDid: this._connectedDid,
                agent: this.agent,
                message
            });
        });
    }
    /**
     * @returns the JSON representation of the permission request
     */
    toJSON() {
        return this._request;
    }
}
//# sourceMappingURL=permission-request.js.map