"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.IccFormXApi = void 0;
const icc_api_1 = require("../icc-api");
const models = require("../icc-api/model/models");
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");
// noinspection JSUnusedGlobalSymbols
class IccFormXApi extends icc_api_1.IccFormApi {
    get headers() {
        return super.headers.then((h) => this.crypto.accessControlKeysHeaders.addAccessControlKeysHeaders(h, utils_1.EntityWithDelegationTypeName.Form));
    }
    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 form with initialised encryption metadata (not in the database).
     * @param user the current user.
     * @param patient the patient this form refers to.
     * @param c initialised data for the form. 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 form.
     */
    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;
            const form = Object.assign(Object.assign({}, (c !== null && c !== void 0 ? c : {})), { _type: 'org.taktik.icure.entities.Form', 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 : [] });
            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 }, (_h = options.sfkOption) !== null && _h !== void 0 ? _h : SecretIdUseOption_1.SecretIdUseOption.UseAnySharedWithParent);
            const extraDelegations = Object.assign(Object.assign({}, (options.ignoreAutoDelegations == true
                ? {}
                : Object.fromEntries([...((_k = (_j = user.autoDelegations) === null || _j === void 0 ? void 0 : _j.all) !== null && _k !== void 0 ? _k : []), ...((_m = (_l = user.autoDelegations) === null || _l === void 0 ? void 0 : _l.medicalInformation) !== null && _m !== void 0 ? _m : [])].map((d) => [d, AccessLevelEnum.WRITE])))), ((_o = options === null || options === void 0 ? void 0 : options.additionalDelegates) !== null && _o !== void 0 ? _o : {}));
            return new models.Form(yield this.crypto.xapi
                .entityWithInitialisedEncryptedMetadata(form, utils_1.EntityWithDelegationTypeName.Form, patient.id, sfk, 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 forms with (allSecretForeignKeysDelimitedByComa, hcpartyId)
     *
     * After these painful steps, you have the forms of the patient.
     * @deprecated use {@link findIdsBy} instead.
     * @param hcpartyId
     * @param patient
     * @param usingPost (Promise)
     */
    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];
            let forms = yield (usingPost
                ? this.findFormsByHCPartyPatientForeignKeysUsingPost(hcpartyId, undefined, undefined, undefined, [...new Set(extractedKeys)])
                : this.findFormsByHCPartyPatientForeignKeys(hcpartyId, [...new Set(extractedKeys)].join(',')));
            return yield this.decrypt(hcpartyId, forms);
        });
    }
    /**
     * Same as {@link findBy} but it will only return the ids of the forms. It can also filter the forms by opening date
     * (the date when the form was opened/started) between startDate and endDate in ascending or descending order by that field (default: ascending).
     * @param hcpartyId the id of the data owner.
     * @param patient the patient whose forms to retrieve.
     * @param startDate optional start date filter (inclusive). Only forms with openingDate >= startDate will be returned.
     * @param endDate optional end date filter (inclusive). Only forms with openingDate <= endDate will be returned.
     * @param descending if true, results are sorted by openingDate in descending order; otherwise in ascending order (default).
     * @return an array of form ids.
     */
    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 this.findFormIdsByDataOwnerPatientOpeningDate(hcpartyId, [...new Set(extractedKeys)], startDate, endDate, descending);
        });
    }
    /**
     * Decrypts the encrypted content of the provided forms.
     * @param hcpartyId the id of the data owner attempting to decrypt the forms.
     * @param forms the forms to decrypt.
     * @return an array of decrypted forms. Forms that could not be decrypted will be returned as-is.
     */
    decrypt(hcpartyId, forms) {
        return __awaiter(this, void 0, void 0, function* () {
            return (yield this.crypto.xapi.tryDecryptEntities(forms, utils_1.EntityWithDelegationTypeName.Form, (x) => new models.Form(x))).map(({ entity }) => entity);
        });
    }
    /**
     * @param form a form
     * @return the id of the patient that the form 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(form) {
        return __awaiter(this, void 0, void 0, function* () {
            return this.crypto.xapi.owningEntityIdsOf({ entity: form, type: utils_1.EntityWithDelegationTypeName.Form }, undefined);
        });
    }
    /**
     * @return if the logged data owner has write access to the content of the given form
     */
    hasWriteAccess(form) {
        return __awaiter(this, void 0, void 0, function* () {
            return this.crypto.xapi.hasWriteAccess({ entity: form, type: utils_1.EntityWithDelegationTypeName.Form });
        });
    }
    /**
     * Share an existing form with other data owners, allowing them to access the non-encrypted data of the form 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 form.
     * @param form the form 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
     * form does not have encrypted content.
     * - sharePatientId: specifies if the id of the patient that this form 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, form_1) {
        return __awaiter(this, arguments, void 0, function* (delegateId, form, options = {}) {
            return this.shareWithMany(form, { [delegateId]: options });
        });
    }
    /**
     * Share an existing form with other data owners, allowing them to access the non-encrypted data of the form and optionally also
     * the encrypted content, with read-only or read-write permissions.
     * @param form the form 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
     * form does not have encrypted content.
     * - sharePatientId: specifies if the id of the patient that this form 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(form, delegates) {
        return __awaiter(this, void 0, void 0, function* () {
            return (yield this.tryShareWithMany(form, delegates)).updatedEntityOrThrow;
        });
    }
    /**
     * Share an existing form with other data owners, allowing them to access the non-encrypted data of the form and optionally also
     * the encrypted content, with read-only or read-write permissions.
     * @param form the form 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
     * form does not have encrypted content.
     * - sharePatientId: specifies if the id of the patient that this form 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(form, 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(form, utils_1.EntityWithDelegationTypeName.Form);
            const updatedEntity = entityWithEncryptionKey ? yield this.modifyForm(entityWithEncryptionKey) : form;
            return this.crypto.xapi
                .simpleShareOrUpdateEncryptedEntityMetadata({
                entity: updatedEntity,
                type: utils_1.EntityWithDelegationTypeName.Form,
            }, Object.fromEntries(Object.entries(delegates).map(([delegateId, options]) => [
                delegateId,
                {
                    requestedPermissions: options.requestedPermissions,
                    shareEncryptionKeys: options.shareEncryptionKey,
                    shareOwningEntityIds: options.sharePatientId,
                    shareSecretIds: options.shareSecretIds,
                },
            ])), (x) => this.bulkShareForms(x))
                .then((r) => r.mapSuccessAsync((e) => this.decrypt(self, [e]).then((es) => es[0])));
        });
    }
    /**
     * Gets all data owners that have access to the given form, along with their access levels.
     * @param entity the form to check.
     * @return an object containing:
     * - permissionsByDataOwnerId: a map of data owner id to their access level.
     * - hasUnknownAnonymousDataOwners: true if there are anonymous data owners with access that could not be identified.
     */
    getDataOwnersWithAccessTo(entity) {
        return this.crypto.delegationsDeAnonymization.getDataOwnersWithAccessTo({ entity, type: utils_1.EntityWithDelegationTypeName.Form });
    }
    /**
     * Retrieves all encryption keys of the given form that are available to the current data owner.
     * @param entity the form whose encryption keys to retrieve.
     * @return an array of encryption keys in hexadecimal string format.
     */
    getEncryptionKeysOf(entity) {
        return this.crypto.xapi.encryptionKeysOf({ entity, type: utils_1.EntityWithDelegationTypeName.Form }, undefined);
    }
    /**
     * Creates or updates de-anonymization metadata for the given form, allowing the delegates to be identified
     * even if they were initially anonymous (e.g., in keyless mode).
     * @param entity the form for which to create de-anonymization metadata.
     * @param delegates the ids of the data owners for which to create de-anonymization information.
     */
    createDelegationDeAnonymizationMetadata(entity, delegates) {
        return this.crypto.delegationsDeAnonymization.createOrUpdateDeAnonymizationInfo({ entity, type: utils_1.EntityWithDelegationTypeName.Form }, delegates);
    }
}
exports.IccFormXApi = IccFormXApi;
//# sourceMappingURL=icc-form-x-api.js.map