All files / tools/src/stateManagement/segmentation SegmentationStateManager.ts

59.2% Statements 164/277
54.13% Branches 72/133
58.9% Functions 43/73
59.2% Lines 164/277

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240                                                                    428x                                       428x                 428x             428x 428x     428x             2829x         658x 658x 658x                 8286x               230x                                       24637x 28862x                                                                                               182x           182x 182x 182x         122x     122x         182x     182x                                                                           230x   230x         230x               230x                       230x 230x 190x 190x     230x 20x               210x                 230x                   230x 296x     230x       230x 230x 222x         230x                           230x                     210x   210x       210x   210x       210x       210x                   210x   210x                                                             210x   210x       210x   210x                                                     210x   210x   210x 210x 210x   40x                                         114x   114x 114x 278x         278x 114x 114x     114x               114x       114x                           114x 114x       114x 40x     114x 114x       114x 114x 114x   114x                                                                                                                                       236x     236x 114x   122x               122x     122x 122x   236x       3244x       3244x                           3244x   3244x       3244x 3244x   3244x                                                                                                                                                           4x   4x 4x         4x 4x   4x   4x           4x   4x     4x                 4x 4x 4x 4x       4x       4x 4x                     4x                                                         4x     4x 4x                 4x 4x                     4x                                                                                                         114x   114x 42x 42x     72x 72x 72x               230x   230x       230x 270x                         12x 12x   12x       12x 16x       12x                 6729x       6729x 7971x     6729x       6729x                                             24250x   24250x 2234x       22016x 5045x     16971x 18693x     18693x     18693x                                           1194x                               1194x         1194x                                                                                                       230x 230x     230x                                                                                                                                                       3358x                                                                                                           230x 230x 230x   230x 210x         20x       428x              
import type { Types } from '@cornerstonejs/core';
import {
  BaseVolumeViewport,
  cache,
  utilities as csUtils,
  getEnabledElementByViewportId,
  volumeLoader,
} from '@cornerstonejs/core';
 
import { SegmentationRepresentations } from '../../enums';
import type {
  ContourRenderingConfig,
  LabelmapRenderingConfig,
  RenderingConfig,
  RepresentationsData,
  Segmentation,
  SegmentationRepresentation,
  SegmentationState,
} from '../../types/SegmentationStateTypes';
import type {
  LabelmapSegmentationDataStack,
  LabelmapSegmentationDataVolume,
} from '../../types/LabelmapTypes';
import vtkColorTransferFunction from '@kitware/vtk.js/Rendering/Core/ColorTransferFunction';
import vtkPiecewiseFunction from '@kitware/vtk.js/Common/DataModel/PiecewiseFunction';
import {
  triggerSegmentationModified,
  triggerSegmentationRemoved,
  triggerSegmentationRepresentationModified,
  triggerSegmentationRepresentationRemoved,
} from './triggerSegmentationEvents';
import { segmentationStyle } from './SegmentationStyle';
import { triggerSegmentationAdded } from './events/triggerSegmentationAdded';
 
const initialDefaultState: SegmentationState = {
  colorLUT: [],
  segmentations: [],
  viewportSegRepresentations: {},
};
 
/**
 * The SegmentationStateManager Class is responsible for managing the state of the
 * segmentations. It stores the segmentations, segmentation representations,
 * and viewport-specific visibility of the representations. It also stores a global
 * config for segmentation rendering. Note that this is a singleton state manager.
 */
export default class SegmentationStateManager {
  private state: Readonly<SegmentationState>;
  public readonly uid: string;
 
  /**
   * A map between segmentationIds and within each segmentation, another
   * map between imageIds and labelmap imageIds.
   */
  private _stackLabelmapImageIdReferenceMap = new Map<
    string,
    Map<string, string>
  >();
 
  /**
   * A map of segmentationId-imageId to the labelmapImageIds that supports segment overlapping
   * meaning that it supports a list of labelmapImageIds for each segmentationId-imageId pair
   */
  private _labelmapImageIdReferenceMap = new Map<string, string[]>();
 
  /**
   * Creates an instance of SegmentationStateManager.
   * @param {string} [uid] - Optional unique identifier for the manager.
   */
  constructor(uid?: string) {
    uid ||= csUtils.uuidv4();
    this.state = Object.freeze(
      csUtils.deepClone(initialDefaultState) as SegmentationState
    );
    this.uid = uid;
  }
 
  /**
   * Returns a copy of the current state of the segmentation.
   */
  getState(): Readonly<SegmentationState> {
    return this.state;
  }
 
  // Helper method to update state immutably
  private updateState(updater: (state: SegmentationState) => void): void {
    const newState = csUtils.deepClone(this.state) as SegmentationState;
    updater(newState);
    this.state = Object.freeze(newState);
  }
 
  /**
   * Returns the colorLUT at the specified index.
   * @param {number} lutIndex - The index of the color LUT to retrieve.
   * @returns {Types.ColorLUT | undefined} A ColorLUT object or undefined if not found.
   */
  getColorLUT(lutIndex: number): Types.ColorLUT | undefined {
    return this.state.colorLUT[lutIndex];
  }
 
  /**
   * Returns the next available color LUT index.
   * @returns {number} The next color LUT index.
   */
  getNextColorLUTIndex(): number {
    return this.state.colorLUT.length;
  }
 
  /**
   * Resets the state to the default state.
   */
  resetState(): void {
    this._stackLabelmapImageIdReferenceMap.clear();
    this._labelmapImageIdReferenceMap.clear();
    this.state = Object.freeze(
      csUtils.deepClone(initialDefaultState) as SegmentationState
    );
  }
 
  /**
   * Returns the segmentation state for the given segmentation ID.
   * @param {string} segmentationId - The ID of the segmentation.
   * @returns {Segmentation | undefined} The segmentation state object or undefined if not found.
   */
  getSegmentation(segmentationId: string): Segmentation | undefined {
    return this.state.segmentations.find(
      (segmentation) => segmentation.segmentationId === segmentationId
    );
  }
 
  /**
   * Updates an existing segmentation with new data.
   *
   * @param segmentationId - The unique identifier of the segmentation to update.
   * @param payload - An object containing the properties to update in the segmentation.
   *
   * @remarks
   * This method updates the state immutably. If the segmentation with the given ID is not found,
   * the method will return without making any changes.
   *
   * @example
   * ```typescript
   * segmentationStateManager.updateSegmentation('seg1', { label: 'newLabel' });
   * ```
   */
  updateSegmentation(
    segmentationId: string,
    payload: Partial<Segmentation>
  ): void {
    this.updateState((draftState) => {
      const segmentation = draftState.segmentations.find(
        (segmentation) => segmentation.segmentationId === segmentationId
      );
 
      if (!segmentation) {
        console.warn(
          `Segmentation with id ${segmentationId} not found. Update aborted.`
        );
        return;
      }
 
      // Directly mutate the draft state
      Object.assign(segmentation, payload);
    });
 
    triggerSegmentationModified(segmentationId);
  }
 
  /**
   * Adds a segmentation to the segmentations array.
   * @param {Segmentation} segmentation - The segmentation object to add.
   * @throws {Error} If a segmentation with the same ID already exists.
   */
  addSegmentation(segmentation: Segmentation): void {
    Iif (this.getSegmentation(segmentation.segmentationId)) {
      throw new Error(
        `Segmentation with id ${segmentation.segmentationId} already exists`
      );
    }
 
    this.updateState((state) => {
      const newSegmentation = csUtils.deepClone(segmentation) as Segmentation;
      if (
        newSegmentation.representationData.Labelmap &&
        'volumeId' in newSegmentation.representationData.Labelmap &&
        !('imageIds' in newSegmentation.representationData.Labelmap)
      ) {
        const imageIds = this.getLabelmapImageIds(
          newSegmentation.representationData
        );
        (
          newSegmentation.representationData
            .Labelmap as LabelmapSegmentationDataStack
        ).imageIds = imageIds;
      }
      state.segmentations.push(newSegmentation);
    });
 
    triggerSegmentationAdded(segmentation.segmentationId);
  }
 
  /**
   * Removes the segmentation from the segmentation state.
   * @param {string} segmentationId - The ID of the segmentation to remove.
   */
  removeSegmentation(segmentationId: string): void {
    this.updateState((state) => {
      // Use Array.prototype.filter to create a new array instead of reassigning
      const filteredSegmentations = state.segmentations.filter(
        (segmentation) => segmentation.segmentationId !== segmentationId
      );
 
      // Update the state with the new filtered array
      state.segmentations.splice(
        0,
        state.segmentations.length,
        ...filteredSegmentations
      );
    });
 
    triggerSegmentationRemoved(segmentationId);
  }
 
  /**
   * Adds a segmentation representation to the specified viewport.
   * @param {string} viewportId - The ID of the viewport.
   * @param {string} segmentationId - The ID of the segmentation.
   * @param {SegmentationRepresentations} type - The type of segmentation representation.
   * @param {RenderingConfig} renderingConfig - The rendering configuration for the segmentation.
   */
  addSegmentationRepresentation(
    viewportId: string,
    segmentationId: string,
    type: SegmentationRepresentations,
    renderingConfig: RenderingConfig
  ): void {
    const enabledElement = getEnabledElementByViewportId(viewportId);
 
    Iif (!enabledElement) {
      return;
    }
 
    // Check if a representation of this type already exists in the viewport
    const existingRepresentations = this.getSegmentationRepresentations(
      viewportId,
      {
        type: type,
        segmentationId,
      }
    );
 
    Iif (existingRepresentations.length > 0) {
      console.debug(
        'A segmentation representation of type',
        type,
        'already exists in viewport',
        viewportId,
        'for segmentation',
        segmentationId
      );
      return;
    }
 
    this.updateState((state) => {
      if (!state.viewportSegRepresentations[viewportId]) {
        state.viewportSegRepresentations[viewportId] = [];
        segmentationStyle.setRenderInactiveSegmentations(viewportId, true);
      }
 
      if (type !== SegmentationRepresentations.Labelmap) {
        this.addDefaultSegmentationRepresentation(
          state,
          viewportId,
          segmentationId,
          type,
          renderingConfig
        );
      } else {
        this.addLabelmapRepresentation(
          state,
          viewportId,
          segmentationId,
          renderingConfig
        );
      }
    });
 
    triggerSegmentationRepresentationModified(viewportId, segmentationId, type);
  }
 
  private addDefaultSegmentationRepresentation(
    state: SegmentationState,
    viewportId: string,
    segmentationId: string,
    type: SegmentationRepresentations,
    renderingConfig: RenderingConfig
  ) {
    const segmentation = state.segmentations.find(
      (segmentation) => segmentation.segmentationId === segmentationId
    );
 
    Iif (!segmentation) {
      return;
    }
 
    const segmentReps = {};
    Object.keys(segmentation.segments).forEach((segmentIndex) => {
      segmentReps[Number(segmentIndex)] = {
        visible: true,
      };
    });
 
    state.viewportSegRepresentations[viewportId].push({
      segmentationId,
      type,
      active: true,
      visible: true,
      // @ts-ignore
      colorLUTIndex: renderingConfig?.colorLUTIndex || 0,
      segments: segmentReps,
      config: {
        ...getDefaultRenderingConfig(type),
        ...renderingConfig,
      },
    });
 
    this._setActiveSegmentation(state, viewportId, segmentationId);
  }
 
  addLabelmapRepresentation(
    state: SegmentationState,
    viewportId: string,
    segmentationId: string,
    renderingConfig: RenderingConfig = getDefaultRenderingConfig(
      SegmentationRepresentations.Labelmap
    )
  ) {
    const enabledElement = getEnabledElementByViewportId(viewportId);
 
    Iif (!enabledElement) {
      return;
    }
 
    const segmentation = this.getSegmentation(segmentationId);
 
    Iif (!segmentation) {
      return;
    }
 
    const { representationData } = segmentation;
 
    // if type is labelmap and we don't have the representation data we need to get it
    // through polySeg so just return
    Iif (!representationData.Labelmap) {
      return this.addDefaultSegmentationRepresentation(
        state,
        viewportId,
        segmentationId,
        SegmentationRepresentations.Labelmap,
        renderingConfig
      );
    }
 
    this.processLabelmapRepresentationAddition(viewportId, segmentationId);
 
    this.addDefaultSegmentationRepresentation(
      state,
      viewportId,
      segmentationId,
      SegmentationRepresentations.Labelmap,
      renderingConfig
    );
  }
 
  /**
   * Processes the addition of a labelmap representation for a given viewport and segmentation.
   * This method handles various scenarios for representation rendering based on the viewport type
   * and the segmentation data.
   *
   * @param viewportId - The ID of the viewport where the labelmap representation will be added.
   * @param segmentationId - The ID of the segmentation to be processed.
   * @param renderingConfig - The configuration for rendering the labelmap representation.
   *
   * @remarks
   * This method handles four main scenarios:
   * 1. Stack Labelmap on Stack Viewport
   * 2. Stack Labelmap on Volume Viewport
   * 3. Volume Labelmap on Stack Viewport
   * 4. Volume Labelmap on Volume Viewport
   *
   * Each scenario requires different processing steps to ensure proper rendering and performance optimization.
   */
  public async processLabelmapRepresentationAddition(
    viewportId: string,
    segmentationId: string
  ) {
    const enabledElement = getEnabledElementByViewportId(viewportId);
 
    Iif (!enabledElement) {
      return;
    }
 
    const segmentation = this.getSegmentation(segmentationId);
 
    Iif (!segmentation) {
      return;
    }
 
    /**
     * Handle various scenarios for representation rendering:
     *
     * 1. Stack Labelmap on Stack Viewport:
     *    For performance, associate each viewport imageId with the correct
     *    labelmap imageId once, then store for later retrieval.
     *
     * 2. Stack Labelmap on Volume Viewport:
     *    Create a volume labelmap from the stack labelmap. Generate a volume
     *    buffer and create separate views for each stack labelmap imageId
     *    to avoid data duplication.
     *
     * 3. Volume Labelmap on Stack Viewport:
     *    Render associated linked imageIds if available. Verify metadata
     *    supports labelmap rendering on the stack viewport. Check for
     *    potential matches between imageIds and labelmap imageIds.
     *
     * 4. Volume Labelmap on Volume Viewport:
     *    Simplest scenario. Ensure the referencedFrameOfReferenceUID
     *    (from referencedVolumeId) matches between labelmap and viewport
     *    before rendering.
     */
    const volumeViewport =
      enabledElement.viewport instanceof BaseVolumeViewport;
 
    const { representationData } = segmentation;
 
    const isBaseVolumeSegmentation = 'volumeId' in representationData.Labelmap;
    const viewport = enabledElement.viewport;
    if (!volumeViewport && !isBaseVolumeSegmentation) {
      // Stack Viewport
      !this.updateLabelmapSegmentationImageReferences(
        viewportId,
        segmentation.segmentationId
      );
    }
  }
 
  /**
   * Helper function to update labelmap segmentation image references.
   * @param {string} segmentationId - The ID of the segmentation representation.
   * @param {Types.IViewport} viewport - The viewport.
   * @param {string[]} labelmapImageIds - The labelmap image IDs.
   * @param {Function} updateCallback - A callback to update the reference map.
   * @returns {string | undefined} The labelmap imageId reference for the current imageId rendered on the viewport.
   */
  _updateLabelmapSegmentationReferences(
    segmentationId,
    viewport,
    labelmapImageIds,
    updateCallback
  ): string | undefined {
    const referenceImageId = viewport.getCurrentImageId();
 
    let viewableLabelmapImageIdFound = false;
    for (const labelmapImageId of labelmapImageIds) {
      const viewableImageId = viewport.isReferenceViewable(
        { referencedImageId: labelmapImageId },
        { asOverlay: true }
      );
 
      if (viewableImageId) {
        viewableLabelmapImageIdFound = true;
        this._stackLabelmapImageIdReferenceMap
          .get(segmentationId)
          .set(referenceImageId, labelmapImageId);
        this._updateLabelmapImageIdReferenceMap({
          segmentationId,
          referenceImageId,
          labelmapImageId,
        });
      }
    }
 
    Iif (updateCallback) {
      updateCallback(viewport, segmentationId, labelmapImageIds);
    }
 
    return viewableLabelmapImageIdFound
      ? this._stackLabelmapImageIdReferenceMap
          .get(segmentationId)
          .get(referenceImageId)
      : undefined;
  }
 
  /**
   * Updates the segmentation image references for a given viewport and segmentation representation.
   * @param {string} viewportId - The ID of the viewport.
   * @param {string} segmentationId - The Id of the segmentation representation.
   * @returns {string | undefined} The labelmap imageId reference for the current imageId rendered on the viewport.
   */
  updateLabelmapSegmentationImageReferences(viewportId, segmentationId) {
    const segmentation = this.getSegmentation(segmentationId);
    Iif (!segmentation) {
      return;
    }
 
    if (!this._stackLabelmapImageIdReferenceMap.has(segmentationId)) {
      this._stackLabelmapImageIdReferenceMap.set(segmentationId, new Map());
    }
 
    const { representationData } = segmentation;
    Iif (!representationData.Labelmap) {
      return;
    }
 
    const labelmapImageIds = this.getLabelmapImageIds(representationData);
    const enabledElement = getEnabledElementByViewportId(viewportId);
    const stackViewport = enabledElement.viewport as Types.IStackViewport;
 
    return this._updateLabelmapSegmentationReferences(
      segmentationId,
      stackViewport,
      labelmapImageIds,
      null
    );
  }
 
  /**
   * Updates all segmentation image references for a given viewport and segmentation representation.
   * @param {string} viewportId - The ID of the viewport.
   * @param {string} segmentationId - The Id of the segmentation representation.
   * @returns {string | undefined} The labelmap imageId reference for the current imageId rendered on the viewport.
   */
  _updateAllLabelmapSegmentationImageReferences(viewportId, segmentationId) {
    const segmentation = this.getSegmentation(segmentationId);
    if (!segmentation) {
      return;
    }
 
    if (!this._stackLabelmapImageIdReferenceMap.has(segmentationId)) {
      this._stackLabelmapImageIdReferenceMap.set(segmentationId, new Map());
    }
 
    const { representationData } = segmentation;
    if (!representationData.Labelmap) {
      return;
    }
 
    const labelmapImageIds = this.getLabelmapImageIds(representationData);
    const enabledElement = getEnabledElementByViewportId(viewportId);
    const stackViewport = enabledElement.viewport as Types.IStackViewport;
 
    this._updateLabelmapSegmentationReferences(
      segmentationId,
      stackViewport,
      labelmapImageIds,
      (stackViewport, segmentationId, labelmapImageIds) => {
        const imageIds = stackViewport.getImageIds();
        imageIds.forEach((referenceImageId, index) => {
          for (const labelmapImageId of labelmapImageIds) {
            const viewableImageId = stackViewport.isReferenceViewable(
              { referencedImageId: labelmapImageId, sliceIndex: index },
              { asOverlay: true, withNavigation: true }
            );
 
            if (viewableImageId) {
              this._stackLabelmapImageIdReferenceMap
                .get(segmentationId)
                .set(referenceImageId, labelmapImageId);
              this._updateLabelmapImageIdReferenceMap({
                segmentationId,
                referenceImageId,
                labelmapImageId,
              });
            }
          }
        });
      }
    );
  }
 
  /**
   * Retrieves the labelmap image IDs for a given representation data.
   * @param {RepresentationsData} representationData - The representation data.
   * @returns {string[]} An array of labelmap image IDs.
   */
  public getLabelmapImageIds(representationData: RepresentationsData) {
    const labelmapData = representationData.Labelmap;
    let labelmapImageIds;
 
    if ((labelmapData as LabelmapSegmentationDataStack).imageIds) {
      labelmapImageIds = (labelmapData as LabelmapSegmentationDataStack)
        .imageIds;
    } else Eif (
      !labelmapImageIds &&
      (labelmapData as LabelmapSegmentationDataVolume).volumeId
    ) {
      // means we are dealing with a volume labelmap that is requested
      // to be rendered on a stack viewport, since we have moved to creating
      // associated imageIds and views for volume we can simply use the
      // volume.imageIds for this
      const volumeId = (labelmapData as LabelmapSegmentationDataVolume)
        .volumeId;
 
      const volume = cache.getVolume(volumeId) as Types.IImageVolume;
      labelmapImageIds = volume.imageIds;
    }
    return labelmapImageIds;
  }
 
  getLabelmapImageIdsForImageId(imageId: string, segmentationId: string) {
    const key = this._generateMapKey({
      segmentationId,
      referenceImageId: imageId,
    });
    return this._labelmapImageIdReferenceMap.get(key);
  }
 
  /**
   * Retrieves the stack labelmap imageIds associated with the current imageId
   * that is rendered on the viewport.
   * @param viewportId - The ID of the viewport.
   * @param segmentationId - The UID of the segmentation representation.
   * @returns A Map object containing the image ID reference map, or undefined if the enabled element is not found.
   */
  getCurrentLabelmapImageIdsForViewport(
    viewportId: string,
    segmentationId: string
  ): string[] | undefined {
    const enabledElement = getEnabledElementByViewportId(viewportId);
 
    Iif (!enabledElement) {
      return;
    }
 
    const stackViewport = enabledElement.viewport as Types.IStackViewport;
    const referenceImageId = stackViewport.getCurrentImageId();
 
    return this.getLabelmapImageIdsForImageId(referenceImageId, segmentationId);
  }
 
  /**
   * Retrieves the stack labelmap imageId associated with the current imageId
   * that is rendered on the viewport.
   * @param viewportId - The ID of the viewport.
   * @param segmentationId - The UID of the segmentation representation.
   * @returns A Map object containing the image ID reference map, or undefined if the enabled element is not found.
   */
  getCurrentLabelmapImageIdForViewport(
    viewportId: string,
    segmentationId: string
  ): string | undefined {
    const enabledElement = getEnabledElementByViewportId(viewportId);
 
    if (!enabledElement) {
      return;
    }
 
    if (!this._stackLabelmapImageIdReferenceMap.has(segmentationId)) {
      return;
    }
 
    const stackViewport = enabledElement.viewport as Types.IStackViewport;
    const currentImageId = stackViewport.getCurrentImageId();
 
    const imageIdReferenceMap =
      this._stackLabelmapImageIdReferenceMap.get(segmentationId);
 
    return imageIdReferenceMap.get(currentImageId);
  }
 
  /**
   * Retrieves all labelmap image IDs associated with a segmentation for a given viewport.
   *
   * @param viewportId - The ID of the viewport.
   * @param segmentationId - The ID of the segmentation.
   * @returns An array of labelmap image IDs. Returns an empty array if the segmentation is not found.
   */
  getStackSegmentationImageIdsForViewport(
    viewportId: string,
    segmentationId: string
  ): string[] {
    const segmentation = this.getSegmentation(segmentationId);
 
    if (!segmentation) {
      return [];
    }
 
    this._updateAllLabelmapSegmentationImageReferences(
      viewportId,
      segmentationId
    );
    const { viewport } = getEnabledElementByViewportId(viewportId);
    const imageIds = viewport.getImageIds();
 
    const associatedReferenceImageAndLabelmapImageIds =
      this._stackLabelmapImageIdReferenceMap.get(segmentationId);
 
    return imageIds.map((imageId) => {
      return associatedReferenceImageAndLabelmapImageIds.get(imageId);
    });
  }
 
  private removeSegmentationRepresentationsInternal(
    viewportId: string,
    specifier?: {
      segmentationId?: string;
      type?: SegmentationRepresentations;
    }
  ): Array<{
    segmentationId: string;
    type: SegmentationRepresentations;
  }> {
    const removedRepresentations: Array<{
      segmentationId: string;
      type: SegmentationRepresentations;
    }> = [];
 
    this.updateState((state) => {
      Iif (!state.viewportSegRepresentations[viewportId]) {
        return;
      }
 
      const currentRepresentations =
        state.viewportSegRepresentations[viewportId];
      let activeRepresentationRemoved = false;
 
      Iif (
        !specifier ||
        Object.values(specifier).every((value) => value === undefined)
      ) {
        // Remove all segmentation representations for the viewport
        removedRepresentations.push(...currentRepresentations);
        delete state.viewportSegRepresentations[viewportId];
      } else {
        const { segmentationId, type } = specifier;
 
        state.viewportSegRepresentations[viewportId] =
          currentRepresentations.filter((representation) => {
            const shouldRemove =
              (segmentationId &&
                type &&
                representation.segmentationId === segmentationId &&
                representation.type === type) ||
              (segmentationId &&
                !type &&
                representation.segmentationId === segmentationId) ||
              (!segmentationId && type && representation.type === type);
 
            Eif (shouldRemove) {
              removedRepresentations.push(representation);
              Eif (representation.active) {
                activeRepresentationRemoved = true;
              }
            }
 
            return !shouldRemove;
          });
 
        // If no representations left for the viewport, remove the viewport entry
        if (state.viewportSegRepresentations[viewportId].length === 0) {
          delete state.viewportSegRepresentations[viewportId];
        } else Eif (activeRepresentationRemoved) {
          // Set the first remaining representation as active
          state.viewportSegRepresentations[viewportId][0].active = true;
        }
      }
 
      // If all representations were removed and there was an active one among them,
      // we don't need to set a new active representation as the viewport entry was deleted.
    });
 
    return removedRepresentations;
  }
 
  /**
   * Removes segmentation representations from a viewport based on the provided specifier.
   *
   * @param viewportId - The ID of the viewport.
   * @param specifier - Optional. An object specifying which representations to remove.
   * @param specifier.segmentationId - Optional. The ID of the segmentation to remove.
   * @param specifier.type - Optional. The type of representation to remove.
   * @returns An array of removed segmentation representations.
   *
   * @remarks
   * If no specifier is provided, all segmentation representations for the viewport are removed.
   * If only segmentationId is provided, all representations of that segmentation are removed.
   * If only type is provided, all representations of that type are removed.
   * If both segmentationId and type are provided, only the specific representation is removed.
   */
  removeSegmentationRepresentations(
    viewportId: string,
    specifier?: {
      segmentationId?: string;
      type?: SegmentationRepresentations;
    }
  ): Array<{
    segmentationId: string;
    type: SegmentationRepresentations;
  }> {
    const removedRepresentations =
      this.removeSegmentationRepresentationsInternal(viewportId, specifier);
 
    // Trigger events for all removed representations
    removedRepresentations.forEach((representation) => {
      triggerSegmentationRepresentationRemoved(
        viewportId,
        representation.segmentationId,
        representation.type
      );
    });
 
    // If there are remaining representations, trigger a modified event for the new active one
    const remainingRepresentations =
      this.getSegmentationRepresentations(viewportId);
    Iif (
      remainingRepresentations.length > 0 &&
      remainingRepresentations[0].active
    ) {
      triggerSegmentationRepresentationModified(
        viewportId,
        remainingRepresentations[0].segmentationId,
        remainingRepresentations[0].type
      );
    }
 
    return removedRepresentations;
  }
 
  /**
   * Removes a specific segmentation representation from a viewport.
   *
   * @param viewportId - The ID of the viewport.
   * @param specifier - An object specifying which representation to remove.
   * @param specifier.segmentationId - The ID of the segmentation to remove.
   * @param specifier.type - The type of representation to remove.
   * @param suppressEvent - Optional. If true, suppresses the removal event trigger.
   * @returns An array of removed segmentation representations (usually containing one item).
   *
   * @remarks
   * This method is more specific than removeSegmentationRepresentations as it requires both
   * segmentationId and type to be provided. It's useful when you need to remove a particular
   * representation without affecting others.
   */
  removeSegmentationRepresentation(
    viewportId: string,
    specifier: {
      segmentationId: string;
      type: SegmentationRepresentations;
    },
    suppressEvent?: boolean
  ): Array<{ segmentationId: string; type: SegmentationRepresentations }> {
    const removedRepresentations =
      this.removeSegmentationRepresentationsInternal(viewportId, specifier);
 
    if (!suppressEvent) {
      removedRepresentations.forEach(({ segmentationId, type }) => {
        triggerSegmentationRepresentationRemoved(
          viewportId,
          segmentationId,
          type
        );
      });
    }
 
    return removedRepresentations;
  }
 
  /**
   * Updates the _labelmapImageIdReferenceMap according to the correct key and preserving old values
   * @param segmentationId
   * @param referenceImageId
   * @param labelmapImageId
   */
  _updateLabelmapImageIdReferenceMap({
    segmentationId,
    referenceImageId,
    labelmapImageId,
  }) {
    const key = this._generateMapKey({ segmentationId, referenceImageId });
 
    if (!this._labelmapImageIdReferenceMap.has(key)) {
      this._labelmapImageIdReferenceMap.set(key, [labelmapImageId]);
      return;
    }
 
    const currentValues = this._labelmapImageIdReferenceMap.get(key);
    const newValues = Array.from(new Set([...currentValues, labelmapImageId]));
    this._labelmapImageIdReferenceMap.set(key, newValues);
  }
 
  _setActiveSegmentation(
    state: SegmentationState,
    viewportId: string,
    segmentationId: string
  ): void {
    const viewport = state.viewportSegRepresentations[viewportId];
 
    Iif (!viewport) {
      return;
    }
 
    viewport.forEach((value) => {
      value.active = value.segmentationId === segmentationId;
    });
  }
 
  /**
   * Sets the active segmentation for a given viewport.
   * @param viewportId - The ID of the viewport.
   * @param segmentationId - The ID of the segmentation to set as active.
   */
  public setActiveSegmentation(
    viewportId: string,
    segmentationId: string
  ): void {
    this.updateState((state) => {
      const viewport = state.viewportSegRepresentations[viewportId];
 
      Iif (!viewport) {
        return;
      }
 
      viewport.forEach((value) => {
        value.active = value.segmentationId === segmentationId;
      });
    });
 
    triggerSegmentationRepresentationModified(viewportId, segmentationId);
  }
 
  /**
   * Retrieves the active segmentation representation for a given viewport.
   * @param viewportId - The ID of the viewport.
   * @returns The active segmentation representation, or undefined if not found.
   */
  getActiveSegmentation(viewportId: string): Segmentation | undefined {
    Iif (!this.state.viewportSegRepresentations[viewportId]) {
      return;
    }
 
    const activeSegRep = this.state.viewportSegRepresentations[viewportId].find(
      (segRep) => segRep.active
    );
 
    Iif (!activeSegRep) {
      return;
    }
 
    return this.getSegmentation(activeSegRep.segmentationId);
  }
 
  /**
   * Retrieves the segmentation representations for a given viewport.
   * @param viewportId - The ID of the viewport.
   * @param specifier - The specifier for the segmentation representations.
   * @returns The segmentation representations for the given viewport, or an empty array if not found.
   *
   * @remarks
   * This method filters the segmentation representations based on the provided specifier.
   * If no specifier is provided, it returns all segmentation representations for the viewport.
   * The filtering is done based on the segmentation type and/or segmentation ID if provided in the specifier.
   * If the viewport has no representations, an empty array is returned.
   */
  getSegmentationRepresentations(
    viewportId: string,
    specifier: {
      segmentationId?: string;
      type?: SegmentationRepresentations;
    } = {}
  ): SegmentationRepresentation[] {
    const viewportRepresentations =
      this.state.viewportSegRepresentations[viewportId];
 
    if (!viewportRepresentations) {
      return [];
    }
 
    // If no specifier is provided, return all entries
    if (!specifier.type && !specifier.segmentationId) {
      return viewportRepresentations;
    }
 
    return viewportRepresentations.filter((representation) => {
      const typeMatch = specifier.type
        ? representation.type === specifier.type
        : true;
      const idMatch = specifier.segmentationId
        ? representation.segmentationId === specifier.segmentationId
        : true;
      return typeMatch && idMatch;
    });
  }
 
  /**
   * Retrieves a specific segmentation representation for a given viewport.
   *
   * @param viewportId - The ID of the viewport.
   * @param specifier - An object specifying the segmentation to retrieve.
   * @param specifier.segmentationId - The ID of the segmentation.
   * @param specifier.type - The type of the segmentation representation.
   * @returns The first matching segmentation representation, or undefined if not found.
   *
   */
  getSegmentationRepresentation(
    viewportId: string,
    specifier: {
      segmentationId: string;
      type: SegmentationRepresentations;
    }
  ): SegmentationRepresentation | undefined {
    // if type is provided, return the first one that matches the type
    return this.getSegmentationRepresentations(viewportId, specifier)[0];
  }
 
  /**
   * Retrieves the visibility of a segmentation representation for a given viewport.
   * @param viewportId - The ID of the viewport.
   * @param specifier - The specifier for the segmentation representation.
   * @returns The visibility of the segmentation representation, or undefined if not found.
   */
  getSegmentationRepresentationVisibility(
    viewportId: string,
    specifier: {
      segmentationId: string;
      type: SegmentationRepresentations;
    }
  ): boolean {
    const viewportRepresentation = this.getSegmentationRepresentation(
      viewportId,
      specifier
    );
 
    return viewportRepresentation?.visible;
  }
 
  /**
   * Sets the visibility of a segmentation representation in a specific viewport.
   * @param viewportId - The ID of the viewport.
   * @param segmentationId - The ID of the segmentation.
   * @param type - The type of the segmentation representation.
   * @param visible - The visibility to set for the segmentation representation in the viewport.
   */
  setSegmentationRepresentationVisibility(
    viewportId: string,
    specifier: {
      segmentationId: string;
      type: SegmentationRepresentations;
    },
    visible: boolean
  ): void {
    this.updateState((state) => {
      const viewportRepresentations = this.getSegmentationRepresentations(
        viewportId,
        specifier
      );
 
      if (!viewportRepresentations) {
        return;
      }
 
      viewportRepresentations.forEach((representation) => {
        representation.visible = visible;
 
        Object.entries(representation.segments).forEach(
          ([segmentIndex, segment]) => {
            segment.visible = visible;
          }
        );
      });
    });
 
    triggerSegmentationRepresentationModified(
      viewportId,
      specifier.segmentationId,
      specifier.type
    );
  }
 
  /**
   * Adds a color LUT to the state.
   * @param colorLUT - The color LUT object to add.
   * @param lutIndex - The index of the color LUT table to add.
   */
  addColorLUT(colorLUT: Types.ColorLUT, lutIndex: number): void {
    this.updateState((state) => {
      Iif (state.colorLUT[lutIndex]) {
        console.warn('Color LUT table already exists, overwriting');
      }
      state.colorLUT[lutIndex] = csUtils.deepClone(colorLUT) as Types.ColorLUT;
    });
  }
 
  /**
   * Removes a color LUT from the state.
   * @param colorLUTIndex - The index of the color LUT table to remove.
   */
  removeColorLUT(colorLUTIndex: number): void {
    this.updateState((state) => {
      delete state.colorLUT[colorLUTIndex];
    });
  }
 
  /**
   * For simplicity we just take the last 15% of the imageId for each
   * and join them
   * @param imageIds - imageIds
   * @returns
   */
  _getStackIdForImageIds(imageIds: string[]): string {
    return imageIds
      .map((imageId) => imageId.slice(-Math.round(imageId.length * 0.15)))
      .join('_');
  }
 
  /**
   * Retrieves all viewport segmentation representations as an array.
   * @returns An array of objects, each containing a viewportId and its associated representations.
   */
  public getAllViewportSegmentationRepresentations(): Array<{
    viewportId: string;
    representations: SegmentationRepresentation[];
  }> {
    return Object.entries(this.state.viewportSegRepresentations).map(
      ([viewportId, representations]) => ({
        viewportId,
        representations,
      })
    );
  }
 
  /**
   * Retrieves all segmentation representations that reference a given segmentation ID.
   * @param {string} segmentationId - The ID of the segmentation.
   * @returns {SegmentationRepresentation[]} An array of segmentation representations.
   */
  getSegmentationRepresentationsBySegmentationId(
    segmentationId: string
  ): { viewportId: string; representations: SegmentationRepresentation[] }[] {
    const result: {
      viewportId: string;
      representations: SegmentationRepresentation[];
    }[] = [];
 
    Object.entries(this.state.viewportSegRepresentations).forEach(
      ([viewportId, viewportReps]) => {
        const filteredReps = viewportReps.filter(
          (representation) => representation.segmentationId === segmentationId
        );
 
        if (filteredReps.length > 0) {
          result.push({ viewportId, representations: filteredReps });
        }
      }
    );
 
    return result;
  }
 
  /**
   * Generates a key for the _labelmapImageIdReferenceMap
   * @param segmentationId - The ID of the segmentation
   * @param referenceImageId - The reference image ID - this is the imageId that is currently being displayed in the viewport (not the derived imageId)
   */
  private _generateMapKey({ segmentationId, referenceImageId }) {
    return `${segmentationId}-${referenceImageId}`;
  }
}
 
async function internalComputeVolumeLabelmapFromStack({
  imageIds,
  options,
}: {
  imageIds: string[];
  options?: {
    volumeId?: string;
  };
}): Promise<{ volumeId: string }> {
  const segmentationImageIds = imageIds;
 
  const volumeId = options?.volumeId || csUtils.uuidv4();
 
  // Todo: fix this
  await volumeLoader.createAndCacheVolumeFromImages(
    volumeId,
    segmentationImageIds
  );
 
  return { volumeId };
}
 
async function internalConvertStackToVolumeLabelmap({
  segmentationId,
  options,
}: {
  segmentationId: string;
  options?: {
    viewportId: string;
    volumeId?: string;
    removeOriginal?: boolean;
  };
}): Promise<void> {
  const segmentation =
    defaultSegmentationStateManager.getSegmentation(segmentationId);
 
  const data = segmentation.representationData
    .Labelmap as LabelmapSegmentationDataStack;
 
  const { volumeId } = await internalComputeVolumeLabelmapFromStack({
    imageIds: data.imageIds,
    options,
  });
 
  (
    segmentation.representationData.Labelmap as LabelmapSegmentationDataVolume
  ).volumeId = volumeId;
}
 
function getDefaultRenderingConfig(type: string): RenderingConfig {
  const cfun = vtkColorTransferFunction.newInstance();
  const ofun = vtkPiecewiseFunction.newInstance();
  ofun.addPoint(0, 0);
 
  if (type === SegmentationRepresentations.Labelmap) {
    return {
      cfun,
      ofun,
    } as LabelmapRenderingConfig;
  } else {
    return {} as ContourRenderingConfig;
  }
}
 
const defaultSegmentationStateManager = new SegmentationStateManager('DEFAULT');
 
export {
  internalConvertStackToVolumeLabelmap,
  internalComputeVolumeLabelmapFromStack,
  defaultSegmentationStateManager,
};