import { getEnabledElementByViewportId } from '@cornerstonejs/core';
import Representations from '../../../enums/SegmentationRepresentations';
import { handleContourSegmentation } from './contourHandler/handleContourSegmentation';
import { getSegmentation } from '../../../stateManagement/segmentation/getSegmentation';
import removeContourFromElement from './removeContourFromElement';
import { getPolySeg } from '../../../config';
import { computeAndAddRepresentation } from '../../../utilities/segmentation/computeAndAddRepresentation';
let polySegConversionInProgress = false;
const processedViewportSegmentations = new Map();
function removeRepresentation(viewportId, segmentationId, renderImmediate = false) {
    const enabledElement = getEnabledElementByViewportId(viewportId);
    if (!enabledElement) {
        return;
    }
    const { viewport } = enabledElement;
    if (!renderImmediate) {
        return;
    }
    removeContourFromElement(viewportId, segmentationId);
    viewport.render();
}
async function render(viewport, contourRepresentation) {
    const { segmentationId } = contourRepresentation;
    const segmentation = getSegmentation(segmentationId);
    if (!segmentation) {
        return;
    }
    let contourData = segmentation.representationData[Representations.Contour];
    if (!contourData &&
        getPolySeg()?.canComputeRequestedRepresentation(segmentationId, Representations.Contour) &&
        !polySegConversionInProgress) {
        polySegConversionInProgress = true;
        const polySeg = getPolySeg();
        contourData = await computeAndAddRepresentation(segmentationId, Representations.Contour, () => polySeg.computeContourData(segmentationId, { viewport }), () => undefined);
        polySegConversionInProgress = false;
    }
    else if (!contourData && !getPolySeg()) {
        console.debug(`No contour data found for segmentationId ${segmentationId} and PolySeg add-on is not configured. Unable to convert from other representations to contour. Please register PolySeg using cornerstoneTools.init({ addons: { polySeg } }) to enable automatic conversion.`);
    }
    if (!contourData) {
        return;
    }
    if (!contourData.geometryIds?.length) {
        return;
    }
    handleContourSegmentation(viewport, contourData.geometryIds, contourData.annotationUIDsMap, contourRepresentation);
}
export default {
    render,
    removeRepresentation,
};
