"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.breakAssociation = void 0;
const arcgis_rest_portal_1 = require("@esri/arcgis-rest-portal");
const get_prop_1 = require("../objects/get-prop");
const getTypeFromEntity_1 = require("../core/getTypeFromEntity");
const updateHubEntity_1 = require("../core/updateHubEntity");
const getAssociationHierarchy_1 = require("./internal/getAssociationHierarchy");
const isAssociationSupported_1 = require("./internal/isAssociationSupported");
const removeAssociationKeyword_1 = require("./internal/removeAssociationKeyword");
const fetchHubEntity_1 = require("../core/fetchHubEntity");
/**
 * When an entity decides it wants to "disconnect" itself
 * from an existing association, half of the association
 * "connection" is broken.
 *
 * from the parent's perspective: the parent removes
 * the child from its association group
 *
 * From the child's perspective: the child removes
 * the parent reference (ref|<parentType>|<parentID>)
 * from its typeKeywords
 *
 * @param entity - entity initiating the disconnection
 * @param type - type of the entity the initiating entity wants to disconnect from
 * @param id - id of the entity the initiating entity wants to disconnect from
 * @param context - contextual portal and auth information
 */
const breakAssociation = async (entity, associationType, id, context) => {
    const entityType = (0, getTypeFromEntity_1.getTypeFromEntity)(entity);
    const isSupported = (0, isAssociationSupported_1.isAssociationSupported)(entityType, associationType);
    if (!isSupported) {
        throw new Error(`breakAssociation: Association between ${entityType} and ${associationType} is not supported.`);
    }
    const associationHierarchy = (0, getAssociationHierarchy_1.getAssociationHierarchy)(entityType);
    const isParent = associationHierarchy.children.includes(associationType);
    if (isParent) {
        const associationGroupId = (0, get_prop_1.getProp)(entity, "associations.groupId");
        const { owner } = await (0, fetchHubEntity_1.fetchHubEntity)(associationType, id, context);
        try {
            await (0, arcgis_rest_portal_1.unshareItemWithGroup)({
                id,
                groupId: associationGroupId,
                authentication: context.session,
                owner,
            });
        }
        catch (err) {
            const error = err;
            throw new Error(`breakAssociation: there was an error unsharing ${id} from ${associationGroupId}: ${error}`);
        }
    }
    else {
        entity.typeKeywords = (0, removeAssociationKeyword_1.removeAssociationKeyword)(entity.typeKeywords, associationType, id);
        await (0, updateHubEntity_1.updateHubEntity)(entityType, entity, context);
    }
};
exports.breakAssociation = breakAssociation;
//# sourceMappingURL=breakAssociation.js.map