"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());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Authorizations = void 0;
const internal_1 = require("../../../../internal");
const types_1 = require("../../../../types");
const conversion_1 = require("../../../../utils/conversion");
/**
 * Handles all Authorization related functionality
 */
class Authorizations extends internal_1.Namespace {
    /**
     * Fetch all pending Authorization Requests for which this Signer is the target
     *
     * @param opts.type - fetch only authorizations of this type. Fetches all types if not passed
     * @param opts.includeExpired - whether to include expired authorizations. Defaults to true
     */
    getReceived(opts) {
        var _a;
        return __awaiter(this, void 0, void 0, function* () {
            const { context, parent, context: { polymeshApi: { rpc }, }, } = this;
            const signerValue = conversion_1.signerToSignerValue(parent);
            const signatory = conversion_1.signerValueToSignatory(signerValue, context);
            const rawBoolean = conversion_1.booleanToBool((_a = opts === null || opts === void 0 ? void 0 : opts.includeExpired) !== null && _a !== void 0 ? _a : true, context);
            let result;
            if (opts === null || opts === void 0 ? void 0 : opts.type) {
                result = yield rpc.identity.getFilteredAuthorizations(signatory, rawBoolean, conversion_1.authorizationTypeToMeshAuthorizationType(opts.type, context));
            }
            else {
                result = yield rpc.identity.getFilteredAuthorizations(signatory, rawBoolean);
            }
            return this.createAuthorizationRequests(result.map(auth => ({ auth, target: signerValue })));
        });
    }
    /**
     * Retrieve a single Authorization Request targeting this Signer by its ID
     *
     * @throws if there is no Authorization Request with the passed ID targeting this Signer
     */
    getOne(args) {
        return __awaiter(this, void 0, void 0, function* () {
            const { context, parent, context: { polymeshApi: { query }, }, } = this;
            const { id } = args;
            const signerValue = conversion_1.signerToSignerValue(parent);
            const signatory = conversion_1.signerValueToSignatory(signerValue, context);
            const rawId = conversion_1.bigNumberToU64(id, context);
            const auth = yield query.identity.authorizations(signatory, rawId);
            if (auth.isNone) {
                throw new internal_1.PolymeshError({
                    code: types_1.ErrorCode.DataUnavailable,
                    message: 'The Authorization Request does not exist',
                });
            }
            return this.createAuthorizationRequests([{ auth: auth.unwrap(), target: signerValue }])[0];
        });
    }
    /**
     * @hidden
     *
     * Create an array of AuthorizationRequests from an array of on-chain Authorizations
     */
    createAuthorizationRequests(auths) {
        const { context } = this;
        return auths
            .map(auth => {
            const { auth: { expiry, auth_id: authId, authorization_data: data, authorized_by: issuer }, target: rawTarget, } = auth;
            const target = conversion_1.signerValueToSigner(rawTarget, context);
            return {
                authId: conversion_1.u64ToBigNumber(authId),
                expiry: expiry.isSome ? conversion_1.momentToDate(expiry.unwrap()) : null,
                data: conversion_1.authorizationDataToAuthorization(data, context),
                target,
                issuer: new internal_1.Identity({ did: conversion_1.identityIdToString(issuer) }, context),
            };
        })
            .filter(({ expiry }) => expiry === null || expiry > new Date())
            .map(args => {
            return new internal_1.AuthorizationRequest(args, context);
        });
    }
}
exports.Authorizations = Authorizations;
//# sourceMappingURL=Authorizations.js.map