"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.IccAccesslogXApi = void 0;
const icc_api_1 = require("../icc-api");
const models_1 = require("../icc-api/model/models");
const collection_utils_1 = require("./utils/collection-utils");
const AuthenticationProvider_1 = require("./auth/AuthenticationProvider");
const SecureDelegation_1 = require("../icc-api/model/SecureDelegation");
const utils_1 = require("./utils");
const SecretIdUseOption_1 = require("./crypto/SecretIdUseOption");
var AccessLevelEnum = SecureDelegation_1.SecureDelegation.AccessLevelEnum;
class IccAccesslogXApi extends icc_api_1.IccAccesslogApi {
    get headers() {
        return super.headers.then((h) => this.crypto.accessControlKeysHeaders.addAccessControlKeysHeaders(h, utils_1.EntityWithDelegationTypeName.AccessLog));
    }
    constructor(host, headers, crypto, dataOwnerApi, autofillAuthor, cryptedKeys = ['detail', 'objectId'], authenticationProvider = new AuthenticationProvider_1.NoAuthenticationProvider(), fetchImpl = typeof window !== 'undefined'
        ? window.fetch
        : typeof self !== 'undefined'
            ? self.fetch
            : fetch) {
        super(host, headers, authenticationProvider, fetchImpl);
        this.autofillAuthor = autofillAuthor;
        this.crypto = crypto;
        this.dataOwnerApi = dataOwnerApi;
        this.encryptedFields = (0, utils_1.parseEncryptedFields)(cryptedKeys, 'AccessLog.');
    }
    /**
     * Creates a new instance of access log with initialised encryption metadata (not in the database).
     * @param user the current user.
     * @param patient the patient this access log refers to.
     * @param h initialised data for the access log. Metadata such as id, creation data, etc. will be automatically initialised, but you can specify
     * other kinds of data or overwrite generated metadata with this. You can't specify encryption metadata.
     * @param options optional parameters:
     * - additionalDelegates: delegates which will have access to the entity in addition to the current data owner and delegates from the
     * auto-delegations. Must be an object which associates each data owner id with the access level to give to that data owner. May overlap with
     * auto-delegations, in such case the access level specified here will be used.
     * - sfkOption: specifies which sfk of the owning entity to use.
     * - ignoreAutoDelegations: if true the data won't be shared with the autodelegations of the user, but only with additional delegates
     * - alternateRootDelegation: by default a new entity is created with a root delegation from self to self. In keyless mode this is not possible,
     * and instead the root delegation will be from self to another. You have to specify which delegate will be part of the root delegation.
     * @return a new instance of access log.
     */
    newInstance(user_1, patient_1, h_1) {
        return __awaiter(this, arguments, void 0, function* (user, patient, h, options = {}) {
            var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r;
            const dataOwnerId = this.dataOwnerApi.getDataOwnerIdOf(user);
            const accessLog = Object.assign(Object.assign({}, (h !== null && h !== void 0 ? h : {})), { _type: 'org.taktik.icure.entities.AccessLog', id: (_a = h === null || h === void 0 ? void 0 : h.id) !== null && _a !== void 0 ? _a : this.crypto.primitives.randomUuid(), created: (_b = h === null || h === void 0 ? void 0 : h.created) !== null && _b !== void 0 ? _b : new Date().getTime(), modified: (_c = h === null || h === void 0 ? void 0 : h.modified) !== null && _c !== void 0 ? _c : new Date().getTime(), date: (_d = h === null || h === void 0 ? void 0 : h.date) !== null && _d !== void 0 ? _d : new Date().getTime(), responsible: (_e = h === null || h === void 0 ? void 0 : h.responsible) !== null && _e !== void 0 ? _e : (this.autofillAuthor ? dataOwnerId : undefined), author: (_f = h === null || h === void 0 ? void 0 : h.author) !== null && _f !== void 0 ? _f : (this.autofillAuthor ? user.id : undefined), codes: (_g = h === null || h === void 0 ? void 0 : h.codes) !== null && _g !== void 0 ? _g : [], tags: (_h = h === null || h === void 0 ? void 0 : h.tags) !== null && _h !== void 0 ? _h : [], user: (_j = h === null || h === void 0 ? void 0 : h.user) !== null && _j !== void 0 ? _j : user.id, accessType: (_k = h === null || h === void 0 ? void 0 : h.accessType) !== null && _k !== void 0 ? _k : 'USER_ACCESS' });
            const ownerId = this.dataOwnerApi.getDataOwnerIdOf(user);
            if (ownerId !== (yield this.dataOwnerApi.getCurrentDataOwnerId()))
                throw new Error('Can only initialise entities as current data owner.');
            const sfk = yield this.crypto.xapi.resolveSecretIdUseOptions({ entity: patient, type: utils_1.EntityWithDelegationTypeName.Patient }, (_l = options.sfkOption) !== null && _l !== void 0 ? _l : SecretIdUseOption_1.SecretIdUseOption.UseAnySharedWithParent);
            const extraDelegations = Object.assign(Object.assign({}, (options.ignoreAutoDelegations == true
                ? {}
                : Object.fromEntries([...((_o = (_m = user.autoDelegations) === null || _m === void 0 ? void 0 : _m.all) !== null && _o !== void 0 ? _o : []), ...((_q = (_p = user.autoDelegations) === null || _p === void 0 ? void 0 : _p.administrativeData) !== null && _q !== void 0 ? _q : [])].map((x) => [x, AccessLevelEnum.WRITE])))), ((_r = options.additionalDelegates) !== null && _r !== void 0 ? _r : {}));
            return new models_1.AccessLog(yield this.crypto.xapi
                .entityWithInitialisedEncryptedMetadata(accessLog, utils_1.EntityWithDelegationTypeName.AccessLog, patient.id, sfk, true, extraDelegations, options.alternateRootDelegation)
                .then((x) => x.updatedEntity));
        });
    }
    /**
     * Creates a new instance of access log with initialised encryption metadata (not in the database).
     * @param user the current user.
     * @param h initialised data for the access log. Metadata such as id, creation data, etc. will be automatically initialised, but you can specify
     * other kinds of data or overwrite generated metadata with this. You can't specify encryption metadata.
     * @param options optional parameters:
     * - additionalDelegates: delegates which will have access to the entity in addition to the current data owner and delegates from the
     * auto-delegations. Must be an object which associates each data owner id with the access level to give to that data owner. May overlap with
     * auto-delegations, in such case the access level specified here will be used.
     * - ignoreAutoDelegations: if true the data won't be shared with the autodelegations of the user, but only with additional delegates
     * - alternateRootDelegation: by default a new entity is created with a root delegation from self to self. In keyless mode this is not possible,
     * and instead the root delegation will be from self to another. You have to specify which delegate will be part of the root delegation.
     * @return a new instance of access log.
     */
    newInstanceNoPatient(user_1, h_1) {
        return __awaiter(this, arguments, void 0, function* (user, h, options = {}) {
            var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q;
            const dataOwnerId = this.dataOwnerApi.getDataOwnerIdOf(user);
            const accessLog = Object.assign(Object.assign({}, (h !== null && h !== void 0 ? h : {})), { _type: 'org.taktik.icure.entities.AccessLog', id: (_a = h === null || h === void 0 ? void 0 : h.id) !== null && _a !== void 0 ? _a : this.crypto.primitives.randomUuid(), created: (_b = h === null || h === void 0 ? void 0 : h.created) !== null && _b !== void 0 ? _b : new Date().getTime(), modified: (_c = h === null || h === void 0 ? void 0 : h.modified) !== null && _c !== void 0 ? _c : new Date().getTime(), date: (_d = h === null || h === void 0 ? void 0 : h.date) !== null && _d !== void 0 ? _d : new Date().getTime(), responsible: (_e = h === null || h === void 0 ? void 0 : h.responsible) !== null && _e !== void 0 ? _e : (this.autofillAuthor ? dataOwnerId : undefined), author: (_f = h === null || h === void 0 ? void 0 : h.author) !== null && _f !== void 0 ? _f : (this.autofillAuthor ? user.id : undefined), codes: (_g = h === null || h === void 0 ? void 0 : h.codes) !== null && _g !== void 0 ? _g : [], tags: (_h = h === null || h === void 0 ? void 0 : h.tags) !== null && _h !== void 0 ? _h : [], user: (_j = h === null || h === void 0 ? void 0 : h.user) !== null && _j !== void 0 ? _j : user.id, accessType: (_k = h === null || h === void 0 ? void 0 : h.accessType) !== null && _k !== void 0 ? _k : 'USER_LOGIN' });
            const ownerId = this.dataOwnerApi.getDataOwnerIdOf(user);
            if (ownerId !== (yield this.dataOwnerApi.getCurrentDataOwnerId()))
                throw new Error('Can only initialise entities as current data owner.');
            const extraDelegations = Object.assign(Object.assign({}, (options.ignoreAutoDelegations == true
                ? {}
                : Object.fromEntries([...((_m = (_l = user.autoDelegations) === null || _l === void 0 ? void 0 : _l.all) !== null && _m !== void 0 ? _m : []), ...((_p = (_o = user.autoDelegations) === null || _o === void 0 ? void 0 : _o.administrativeData) !== null && _p !== void 0 ? _p : [])].map((x) => [x, AccessLevelEnum.WRITE])))), ((_q = options.additionalDelegates) !== null && _q !== void 0 ? _q : {}));
            return new models_1.AccessLog(yield this.crypto.xapi
                .entityWithInitialisedEncryptedMetadata(accessLog, utils_1.EntityWithDelegationTypeName.AccessLog, undefined, undefined, true, extraDelegations, options.alternateRootDelegation)
                .then((x) => x.updatedEntity));
        });
    }
    // noinspection JSUnusedGlobalSymbols
    /**
     * 1. Check whether there is a delegation with 'hcpartyId' or not.
     * 2. 'fetchHcParty[hcpartyId][1]': is encrypted AES exchange key by RSA public key of him.
     * 3. Obtain the AES exchange key, by decrypting the previous step value with hcparty private key
     *      3.1.  KeyPair should be fetch from cache (in jwk)
     *      3.2.  if it doesn't exist in the cache, it has to be loaded from Browser Local store, and then import it to WebCrypto
     * 4. Obtain the array of delegations which are delegated to his ID (hcpartyId) in this patient
     * 5. Decrypt and collect all keys (secretForeignKeys) within delegations of previous step (with obtained AES key of step 4)
     * 6. Do the REST call to get all access logs with (allSecretForeignKeysDelimitedByComma, hcpartyId)
     *
     * After these painful steps, you have the access logs of the patient.
     *
     * @deprecated use {@link findIdsBy} instead
     * @param hcpartyId
     * @param patient (Promise)
     * @param usingPost
     */
    findBy(hcpartyId_1, patient_1) {
        return __awaiter(this, arguments, void 0, function* (hcpartyId, patient, usingPost = false) {
            const extractedKeys = yield this.crypto.xapi.secretIdsOf({ entity: patient, type: utils_1.EntityWithDelegationTypeName.Patient }, hcpartyId);
            const topmostParentId = (yield this.dataOwnerApi.getCurrentDataOwnerHierarchyIds())[0];
            return extractedKeys && extractedKeys.length > 0
                ? usingPost
                    ? this.findByHCPartyPatientSecretFKeysArray(hcpartyId, [...new Set(extractedKeys)])
                    : this.findByHCPartyPatientSecretFKeys(hcpartyId, [...new Set(extractedKeys)].join(','))
                : Promise.resolve([]);
        });
    }
    /**
     * Same as `findBy` but it will only return the ids of the access logs. It can also filter the access logs where AccessLog.date is between
     * startDate and endDate in ascending or descending order by that field. (default: ascending).
     */
    findIdsBy(hcpartyId, patient, startDate, endDate, descending) {
        return __awaiter(this, void 0, void 0, function* () {
            const extractedKeys = yield this.crypto.xapi.secretIdsOf({ entity: patient, type: utils_1.EntityWithDelegationTypeName.Patient }, hcpartyId);
            return extractedKeys && extractedKeys.length > 0
                ? this.findAccessLogIdsByDataOwnerPatientDate(hcpartyId, [...new Set(extractedKeys)], startDate, endDate, descending)
                : Promise.resolve([]);
        });
    }
    /**
     * @deprecated use {@link findAccessLogIdsByDataOwnerPatientDate} instead
     */
    findByHCPartyPatientSecretFKeys(hcPartyId, secretFKeys) {
        const _super = Object.create(null, {
            findAccessLogsByHCPartyPatientForeignKeys: { get: () => super.findAccessLogsByHCPartyPatientForeignKeys }
        });
        return __awaiter(this, void 0, void 0, function* () {
            const accessLogs = yield _super.findAccessLogsByHCPartyPatientForeignKeys.call(this, hcPartyId, secretFKeys);
            return yield this.decrypt(hcPartyId, accessLogs);
        });
    }
    /**
     * @deprecated use {@link findAccessLogIdsByDataOwnerPatientDate} instead
     */
    findByHCPartyPatientSecretFKeysArray(hcPartyId, secretFKeys) {
        return super.findAccessLogsByHCPartyPatientForeignKeysUsingPost(hcPartyId, secretFKeys).then((accesslogs) => this.decrypt(hcPartyId, accesslogs));
    }
    /**
     * Decrypts a list of access logs using the current data owner's keys.
     * @param hcpId the id of the healthcare party performing the decryption.
     * @param accessLogs the access logs to decrypt.
     * @return the decrypted access logs.
     */
    decrypt(hcpId, accessLogs) {
        return __awaiter(this, void 0, void 0, function* () {
            return (yield this.crypto.xapi.tryDecryptEntities(accessLogs, utils_1.EntityWithDelegationTypeName.AccessLog, (json) => new models_1.AccessLog(json))).map(({ entity }) => entity);
        });
    }
    /**
     * Encrypts the encrypted fields of a list of access logs.
     * @param user the current user, used to determine the data owner for encryption.
     * @param accessLogs the access logs to encrypt.
     * @return the encrypted access logs.
     */
    encrypt(user, accessLogs) {
        const owner = this.dataOwnerApi.getDataOwnerIdOf(user);
        return this.encryptAs(owner, accessLogs);
    }
    encryptAs(dataOwner, accessLogs) {
        return __awaiter(this, void 0, void 0, function* () {
            return this.crypto.xapi.tryEncryptEntities(accessLogs, utils_1.EntityWithDelegationTypeName.AccessLog, this.encryptedFields, false, false, (json) => new models_1.AccessLog(json));
        });
    }
    /**
     * @throws always. Use {@link createAccessLogWithUser} instead.
     */
    createAccessLog(body) {
        throw new Error('Cannot call a method that returns access logs without providing a user for de/encryption');
    }
    /**
     * Creates an access log after encrypting its content.
     * @param user the current user, used for encryption.
     * @param body the access log to create.
     * @return the created and decrypted access log.
     */
    createAccessLogWithUser(user, body) {
        return body
            ? this.encrypt(user, [(0, collection_utils_1.cloneDeep)(body)])
                .then((als) => super.createAccessLog(als[0]))
                .then((accessLog) => this.decrypt(this.dataOwnerApi.getDataOwnerIdOf(user), [accessLog]))
                .then((als) => als[0])
            : Promise.resolve();
    }
    /**
     * @throws always. Use {@link getAccessLogWithUser} instead.
     */
    getAccessLog(accessLogId) {
        throw new Error('Cannot call a method that returns access logs without providing a user for de/encryption');
    }
    /**
     * Retrieves an access log by id and decrypts it.
     * @param user the current user, used for decryption.
     * @param accessLogId the id of the access log to retrieve.
     * @return the decrypted access log.
     */
    getAccessLogWithUser(user, accessLogId) {
        return super
            .getAccessLog(accessLogId)
            .then((accessLog) => this.decrypt(this.dataOwnerApi.getDataOwnerIdOf(user), [accessLog]))
            .then((als) => als[0]);
    }
    /**
     * @throws always. Use {@link getAccessLogsWithUser} instead.
     */
    getAccessLogs(ids) {
        return __awaiter(this, void 0, void 0, function* () {
            throw new Error('Cannot call a method that returns access logs without providing a user for de/encryption');
        });
    }
    /**
     * Retrieves multiple access logs by their ids and decrypts them.
     * @param user the current user, used for decryption.
     * @param ids the list of access log ids to retrieve.
     * @return the decrypted access logs.
     */
    getAccessLogsWithUser(user, ids) {
        return super.getAccessLogs(ids).then((accessLogs) => this.decrypt(this.dataOwnerApi.getDataOwnerIdOf(user), accessLogs));
    }
    /**
     * @throws always. Use {@link listAccessLogsWithUser} instead.
     */
    listAccessLogs(fromEpoch, toEpoch, startKey, startDocumentId, limit) {
        throw new Error('Cannot call a method that returns access logs without providing a user for de/encryption');
    }
    /**
     * Lists access logs within a date range and decrypts them.
     * @param user the current user, used for decryption.
     * @param fromEpoch the start of the date range (epoch in ms).
     * @param toEpoch the end of the date range (epoch in ms).
     * @param startKey the pagination start key.
     * @param startDocumentId the pagination start document id.
     * @param limit the maximum number of results to return.
     * @param descending if true, results are returned in descending order.
     * @return a paginated list of decrypted access logs.
     */
    listAccessLogsWithUser(user, fromEpoch, toEpoch, startKey, startDocumentId, limit, descending) {
        return super
            .listAccessLogs(fromEpoch, toEpoch, startKey, startDocumentId, limit, descending)
            .then((accessLog) => this.decrypt(this.dataOwnerApi.getDataOwnerIdOf(user), accessLog.rows).then((dr) => Object.assign(accessLog, { rows: dr })));
    }
    /**
     * @throws always. Use {@link modifyAccessLogWithUser} instead.
     */
    modifyAccessLog(body) {
        throw new Error('Cannot call a method that returns access logs without providing a user for de/encryption');
    }
    /**
     * Modifies an access log after encrypting its content.
     * @param user the current user, used for encryption/decryption.
     * @param body the access log with updated fields.
     * @return the modified and decrypted access log, or null if body was not provided.
     */
    modifyAccessLogWithUser(user, body) {
        return __awaiter(this, void 0, void 0, function* () {
            return body ? this.modifyAs(this.dataOwnerApi.getDataOwnerIdOf(user), (0, collection_utils_1.cloneDeep)(body)) : null;
        });
    }
    modifyAs(owner, body) {
        const _super = Object.create(null, {
            modifyAccessLog: { get: () => super.modifyAccessLog }
        });
        return __awaiter(this, void 0, void 0, function* () {
            return this.encryptAs(owner, [(0, collection_utils_1.cloneDeep)(body)])
                .then((als) => _super.modifyAccessLog.call(this, als[0]))
                .then((accessLog) => this.decrypt(owner, [accessLog]))
                .then((als) => als[0]);
        });
    }
    /**
     * @throws always. Use {@link findByUserAfterDateWithUser} instead.
     */
    findByUserAfterDate(userId, accessType, startDate, startKey, startDocumentId, limit, descending) {
        throw new Error('Cannot call a method that returns access logs without providing a user for de/encryption');
    }
    /**
     * Finds access logs by user id after a given date and decrypts them.
     * @param user the current user, used for decryption.
     * @param userId the id of the user whose access logs to find.
     * @param accessType optional access type filter.
     * @param startDate optional start date filter (epoch in ms).
     * @param startKey the pagination start key.
     * @param startDocumentId the pagination start document id.
     * @param limit the maximum number of results to return.
     * @param descending if true, results are returned in descending order.
     * @return a paginated list of decrypted access logs.
     */
    findByUserAfterDateWithUser(user, userId, accessType, startDate, startKey, startDocumentId, limit, descending) {
        return super
            .findByUserAfterDate(userId, accessType, startDate, startKey, startDocumentId, limit, descending)
            .then((accessLog) => this.decrypt(this.dataOwnerApi.getDataOwnerIdOf(user), accessLog.rows).then((dr) => Object.assign(accessLog, { rows: dr })));
    }
    /**
     * @param accessLog an access log
     * @return the id of the patient that the access log refers to, retrieved from the encrypted metadata (not from the decrypted entity body). Normally
     * there should only be one element in the returned array, but in case of entity merges there could be multiple values.
     */
    decryptPatientIdOf(accessLog) {
        return __awaiter(this, void 0, void 0, function* () {
            return this.crypto.xapi.owningEntityIdsOf({ entity: accessLog, type: utils_1.EntityWithDelegationTypeName.AccessLog }, undefined);
        });
    }
    /**
     * @return if the logged data owner has write access to the content of the given access log
     */
    hasWriteAccess(accessLog) {
        return __awaiter(this, void 0, void 0, function* () {
            return this.crypto.xapi.hasWriteAccess({ entity: accessLog, type: utils_1.EntityWithDelegationTypeName.AccessLog });
        });
    }
    /**
     * Share an existing access log with other data owners, allowing them to access the non-encrypted data of the access log and optionally also the
     * encrypted content, with read-only or read-write permissions.
     * @param delegateId the id of the data owner which will be granted access to the access log.
     * @param accessLog the access log to share.
     * @param options optional parameters to customize the sharing behaviour:
     * - shareSecretIds: specifies which secret ids of the entity should be shared. If not provided all secret ids available to the current user will be shared
     * - shareEncryptionKey: specifies if the encryption key of the access log should be shared with the delegate, giving access to all encrypted
     * content of the entity, excluding other encrypted metadata (defaults to {@link ShareMetadataBehaviour.IF_AVAILABLE}).
     * - sharePatientId: specifies if the id of the patient that this access log refers to should be shared with the delegate. Normally this would
     * be the same as objectId, but it is encrypted separately from it allowing you to give access to the patient id without giving access to the other
     * encrypted data of the access log (defaults to {@link ShareMetadataBehaviour.IF_AVAILABLE}).
     * - requestedPermissions: the requested permissions for the delegate, defaults to {@link RequestedPermissionEnum.MAX_WRITE}.
     * @return the updated entity
     */
    shareWith(delegateId_1, accessLog_1) {
        return __awaiter(this, arguments, void 0, function* (delegateId, accessLog, options = {}) {
            return this.shareWithMany(accessLog, { [delegateId]: options });
        });
    }
    /**
     * Share an existing access log with other data owners, allowing them to access the non-encrypted data of the access log and optionally also the
     * encrypted content, with read-only or read-write permissions.
     * @param accessLog the access log to share.
     * @param delegates associates the id of data owners which will be granted access to the entity, to the following sharing options:
     * - shareSecretIds: specifies which secret ids of the entity should be shared. If not provided all secret ids available to the current user will be shared
     * - shareEncryptionKey: specifies if the encryption key of the access log should be shared with the delegate, giving access to all encrypted
     * content of the entity, excluding other encrypted metadata (defaults to {@link ShareMetadataBehaviour.IF_AVAILABLE}).
     * - sharePatientId: specifies if the id of the patient that this access log refers to should be shared with the delegate. Normally this would
     * be the same as objectId, but it is encrypted separately from it allowing you to give access to the patient id without giving access to the other
     * encrypted data of the access log (defaults to {@link ShareMetadataBehaviour.IF_AVAILABLE}).
     * - requestedPermissions: the requested permissions for the delegate, defaults to {@link RequestedPermissionEnum.MAX_WRITE}.
     * @return the updated entity
     */
    shareWithMany(accessLog, delegates) {
        return __awaiter(this, void 0, void 0, function* () {
            return (yield this.tryShareWithMany(accessLog, delegates)).updatedEntityOrThrow;
        });
    }
    /**
     * Share an existing access log with other data owners, allowing them to access the non-encrypted data of the access log and optionally also the
     * encrypted content, with read-only or read-write permissions.
     * @param accessLog the access log to share.
     * @param delegates associates the id of data owners which will be granted access to the entity, to the following sharing options:
     * - shareSecretIds: specifies which secret ids of the entity should be shared. If not provided all secret ids available to the current user will be shared
     * - shareEncryptionKey: specifies if the encryption key of the access log should be shared with the delegate, giving access to all encrypted
     * content of the entity, excluding other encrypted metadata (defaults to {@link ShareMetadataBehaviour.IF_AVAILABLE}).
     * - sharePatientId: specifies if the id of the patient that this access log refers to should be shared with the delegate. Normally this would
     * be the same as objectId, but it is encrypted separately from it allowing you to give access to the patient id without giving access to the other
     * encrypted data of the access log (defaults to {@link ShareMetadataBehaviour.IF_AVAILABLE}).
     * - requestedPermissions: the requested permissions for the delegate, defaults to {@link RequestedPermissionEnum.MAX_WRITE}.
     * @return a promise which will contain the result of the operation: the updated entity if the operation was successful or details of the error if
     * the operation failed.
     */
    tryShareWithMany(accessLog, delegates) {
        return __awaiter(this, void 0, void 0, function* () {
            const self = yield this.dataOwnerApi.getCurrentDataOwnerId();
            // All entities should have an encryption key.
            const entityWithEncryptionKey = yield this.crypto.xapi.ensureEncryptionKeysInitialised(accessLog, utils_1.EntityWithDelegationTypeName.AccessLog);
            const updatedEntity = entityWithEncryptionKey ? yield this.modifyAs(self, entityWithEncryptionKey) : accessLog;
            return this.crypto.xapi
                .simpleShareOrUpdateEncryptedEntityMetadata({
                entity: updatedEntity,
                type: utils_1.EntityWithDelegationTypeName.AccessLog,
            }, Object.fromEntries(Object.entries(delegates).map(([delegateId, options]) => [
                delegateId,
                {
                    requestedPermissions: options.requestedPermissions,
                    shareEncryptionKeys: options.shareEncryptionKey,
                    shareOwningEntityIds: options.sharePatientId,
                    shareSecretIds: options.shareSecretIds,
                },
            ])), (x) => this.bulkShareAccessLogs(x))
                .then((r) => r.mapSuccessAsync((e) => this.decrypt(self, [e]).then((es) => es[0])));
        });
    }
    /**
     * Retrieves the data owners that have access to the given access log, along with their access levels.
     * @param entity the access log.
     * @return an object containing a map of data owner ids to their access levels, and a flag indicating if there are unknown anonymous data owners.
     */
    getDataOwnersWithAccessTo(entity) {
        return this.crypto.delegationsDeAnonymization.getDataOwnersWithAccessTo({ entity, type: utils_1.EntityWithDelegationTypeName.AccessLog });
    }
    /**
     * Retrieves the encryption keys of the given access log.
     * @param entity the access log.
     * @return the encryption key ids.
     */
    getEncryptionKeysOf(entity) {
        return this.crypto.xapi.encryptionKeysOf({ entity, type: utils_1.EntityWithDelegationTypeName.AccessLog }, undefined);
    }
    /**
     * Creates or updates de-anonymization metadata for the given access log, allowing the specified delegates to
     * identify the data owners that have access to it.
     * @param entity the access log.
     * @param delegates the data owner ids for which to create de-anonymization metadata.
     */
    createDelegationDeAnonymizationMetadata(entity, delegates) {
        return this.crypto.delegationsDeAnonymization.createOrUpdateDeAnonymizationInfo({ entity, type: utils_1.EntityWithDelegationTypeName.AccessLog }, delegates);
    }
}
exports.IccAccesslogXApi = IccAccesslogXApi;
//# sourceMappingURL=icc-accesslog-x-api.js.map