import { cache, metaData, utilities } from "@cornerstonejs/core";
import vtkPiecewiseFunction from "@kitware/vtk.js/Common/DataModel/PiecewiseFunction";

export default function setMipTransferFunctionForVolumeActor({
  volumeActor,
  volumeId,
}) {
  const mapper = volumeActor.getMapper?.();
  if (mapper?.setSampleDistance) {
    mapper.setSampleDistance(1.0);
  }
  const rgbTransferFunction = volumeActor
    .getProperty()
    .getRGBTransferFunction(0);
  let range = null;
  const imageVolume = volumeId ? cache.getVolume(volumeId) : null;
  const imageId = imageVolume?.imageIds?.[0];
  if (imageId) {
    const voiLutModule = metaData.get("voiLutModule", imageId);
    const rawCenter = Array.isArray(voiLutModule?.windowCenter)
      ? voiLutModule.windowCenter[0]
      : voiLutModule?.windowCenter;
    const rawWidth = Array.isArray(voiLutModule?.windowWidth)
      ? voiLutModule.windowWidth[0]
      : voiLutModule?.windowWidth;
    const center = Number(rawCenter);
    const width = Number(rawWidth);
    if (Number.isFinite(center) && Number.isFinite(width) && width > 0) {
      const upper = center + width / 2;
      range = [0, upper];
    } else if (Number.isFinite(center)) {
      range = [0, center];
    }
  }
  if (!range) {
    range = [0, 5];
  }

  rgbTransferFunction.setRange(range[0], range[1]);
  utilities.invertRgbTransferFunction(rgbTransferFunction);
  const upper = Number(range[1]);
  if (Number.isFinite(upper) && upper > 0) {
    const ofun = vtkPiecewiseFunction.newInstance();
    ofun.addPoint(0, 0.0);
    ofun.addPoint(upper * 0.02, 0.9);
    ofun.addPoint(upper, 1.0);
    volumeActor.getProperty().setScalarOpacity(0, ofun);
  }
}
