"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.IccClassificationXApi = void 0;
const icc_api_1 = require("../icc-api");
const models = require("../icc-api/model/models");
const date_fns_1 = require("date-fns");
const AuthenticationProvider_1 = require("./auth/AuthenticationProvider");
const SecureDelegation_1 = require("../icc-api/model/SecureDelegation");
var AccessLevelEnum = SecureDelegation_1.SecureDelegation.AccessLevelEnum;
const utils_1 = require("./utils");
const SecretIdUseOption_1 = require("./crypto/SecretIdUseOption");
class IccClassificationXApi extends icc_api_1.IccClassificationApi {
    get headers() {
        return super.headers.then((h) => this.crypto.accessControlKeysHeaders.addAccessControlKeysHeaders(h, utils_1.EntityWithDelegationTypeName.Classification));
    }
    constructor(host, headers, crypto, dataOwnerApi, autofillAuthor, 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;
    }
    /**
     * Creates a new instance of classification with initialised encryption metadata (not in the database).
     * @param user the current user.
     * @param patient the patient this classification refers to.
     * @param c initialised data for the classification. 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 classification.
     */
    newInstance(user_1, patient_1) {
        return __awaiter(this, arguments, void 0, function* (user, patient, c = {}, options = {}) {
            var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q;
            const classification = Object.assign(Object.assign({}, (c !== null && c !== void 0 ? c : {})), { _type: 'org.taktik.icure.entities.Classification', id: (_a = c === null || c === void 0 ? void 0 : c.id) !== null && _a !== void 0 ? _a : this.crypto.primitives.randomUuid(), created: (_b = c === null || c === void 0 ? void 0 : c.created) !== null && _b !== void 0 ? _b : new Date().getTime(), modified: (_c = c === null || c === void 0 ? void 0 : c.modified) !== null && _c !== void 0 ? _c : new Date().getTime(), responsible: (_d = c === null || c === void 0 ? void 0 : c.responsible) !== null && _d !== void 0 ? _d : (this.autofillAuthor ? this.dataOwnerApi.getDataOwnerIdOf(user) : undefined), author: (_e = c === null || c === void 0 ? void 0 : c.author) !== null && _e !== void 0 ? _e : (this.autofillAuthor ? user.id : undefined), codes: (_f = c === null || c === void 0 ? void 0 : c.codes) !== null && _f !== void 0 ? _f : [], tags: (_g = c === null || c === void 0 ? void 0 : c.tags) !== null && _g !== void 0 ? _g : [], healthElementId: (_h = c === null || c === void 0 ? void 0 : c.healthElementId) !== null && _h !== void 0 ? _h : this.crypto.primitives.randomUuid(), openingDate: (_j = c === null || c === void 0 ? void 0 : c.openingDate) !== null && _j !== void 0 ? _j : parseInt((0, date_fns_1.format)(new Date(), 'yyyyMMddHHmmss')) });
            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 }, (_k = options.sfkOption) !== null && _k !== void 0 ? _k : SecretIdUseOption_1.SecretIdUseOption.UseAnySharedWithParent);
            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.medicalInformation) !== null && _p !== void 0 ? _p : [])].map((d) => [d, AccessLevelEnum.WRITE])))), ((_q = options === null || options === void 0 ? void 0 : options.additionalDelegates) !== null && _q !== void 0 ? _q : {}));
            return new models.Classification(yield this.crypto.xapi
                .entityWithInitialisedEncryptedMetadata(classification, utils_1.EntityWithDelegationTypeName.Classification, patient === null || patient === void 0 ? void 0 : patient.id, sfk, true, extraDelegations, options.alternateRootDelegation)
                .then((x) => x.updatedEntity));
        });
    }
    /**
     * @deprecated use {@link findIdsBy} instead.
     */
    findBy(hcpartyId, patient) {
        return __awaiter(this, void 0, void 0, function* () {
            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
                ? this.findClassificationsByHCPartyPatientForeignKeys(topmostParentId, [...new Set(extractedKeys)].join(','))
                : Promise.resolve([]);
        });
    }
    /**
     * Same as {@link findBy} but it will only return the ids of the classifications. It can also filter the classifications where
     * Classification.created 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);
            const topmostParentId = (yield this.dataOwnerApi.getCurrentDataOwnerHierarchyIds())[0];
            return extractedKeys && extractedKeys.length > 0
                ? this.findClassificationIdsByDataOwnerPatientCreated(topmostParentId, [...new Set(extractedKeys)], startDate, endDate, descending)
                : Promise.resolve([]);
        });
    }
    /**
     * @param classification a classification
     * @return the id of the patient that the classification refers to, retrieved from the encrypted metadata. Normally there should only be one element
     * in the returned array, but in case of entity merges there could be multiple values.
     */
    decryptPatientIdOf(classification) {
        return __awaiter(this, void 0, void 0, function* () {
            return this.crypto.xapi.owningEntityIdsOf({ entity: classification, type: utils_1.EntityWithDelegationTypeName.Classification }, undefined);
        });
    }
    /**
     * @return if the logged data owner has write access to the content of the given classification
     */
    hasWriteAccess(classification) {
        return __awaiter(this, void 0, void 0, function* () {
            return this.crypto.xapi.hasWriteAccess({ entity: classification, type: utils_1.EntityWithDelegationTypeName.Classification });
        });
    }
    /**
     * Share an existing classification with other data owners, allowing them to access the non-encrypted data of the classification 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 classification.
     * @param classification the classification 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}). Note that by default a
     * classification does not have encrypted content.
     * - sharePatientId: specifies if the id of the patient that this classification refers to should be shared with the delegate (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, classification_1) {
        return __awaiter(this, arguments, void 0, function* (delegateId, classification, options = {}) {
            return this.shareWithMany(classification, { [delegateId]: options });
        });
    }
    /**
     * Share an existing classification with other data owners, allowing them to access the non-encrypted data of the classification and optionally also
     * the encrypted content, with read-only or read-write permissions.
     * @param classification the classification 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}). Note that by default a
     * classification does not have encrypted content.
     * - sharePatientId: specifies if the id of the patient that this classification refers to should be shared with the delegate (defaults to
     * {@link ShareMetadataBehaviour.IF_AVAILABLE}).
     * - requestedPermissions: the requested permissions for the delegate, defaults to {@link RequestedPermissionEnum.MAX_WRITE}.
     * @return the updated entity
     */
    shareWithMany(classification, delegates) {
        return __awaiter(this, void 0, void 0, function* () {
            return (yield this.tryShareWithMany(classification, delegates)).updatedEntityOrThrow;
        });
    }
    /**
     * Share an existing classification with other data owners, allowing them to access the non-encrypted data of the classification and optionally also
     * the encrypted content, with read-only or read-write permissions.
     * @param classification the classification 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}). Note that by default a
     * classification does not have encrypted content.
     * - sharePatientId: specifies if the id of the patient that this classification refers to should be shared with the delegate (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(classification, delegates) {
        return __awaiter(this, void 0, void 0, function* () {
            // All entities should have an encryption key.
            const entityWithEncryptionKey = yield this.crypto.xapi.ensureEncryptionKeysInitialised(classification, utils_1.EntityWithDelegationTypeName.Classification);
            const updatedEntity = entityWithEncryptionKey ? yield this.modifyClassification(entityWithEncryptionKey) : classification;
            return this.crypto.xapi.simpleShareOrUpdateEncryptedEntityMetadata({
                entity: updatedEntity,
                type: utils_1.EntityWithDelegationTypeName.Classification,
            }, Object.fromEntries(Object.entries(delegates).map(([delegateId, options]) => [
                delegateId,
                {
                    requestedPermissions: options.requestedPermissions,
                    shareEncryptionKeys: options.shareEncryptionKey,
                    shareOwningEntityIds: options.sharePatientId,
                    shareSecretIds: options.shareSecretIds,
                },
            ])), (x) => this.bulkShareClassifications(x));
        });
    }
    /**
     * Retrieves the data owners that have access to the given classification, along with their access levels.
     * @param entity the classification.
     * @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.Classification });
    }
    /**
     * Retrieves the encryption keys of the given classification.
     * @param entity the classification.
     * @return the encryption key ids.
     */
    getEncryptionKeysOf(entity) {
        return this.crypto.xapi.encryptionKeysOf({ entity, type: utils_1.EntityWithDelegationTypeName.Classification }, undefined);
    }
    /**
     * Creates or updates de-anonymization metadata for the given classification, allowing the specified delegates to
     * identify the data owners that have access to it.
     * @param entity the classification.
     * @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.Classification }, delegates);
    }
}
exports.IccClassificationXApi = IccClassificationXApi;
//# sourceMappingURL=icc-classification-x-api.js.map