import vtkColorTransferFunction from "@kitware/vtk.js/Rendering/Core/ColorTransferFunction";
import vtkPiecewiseFunction from "@kitware/vtk.js/Common/DataModel/PiecewiseFunction";
import { Scale } from "@kitware/vtk.js/Rendering/Core/ColorTransferFunction/Constants";
import { cache, metaData, utilities } from "@cornerstonejs/core";

const { getColormap } = utilities.colormap;

function getWindowCenterFromVolumeId(volumeId) {
  if (!volumeId) return null;
  const imageVolume = cache.getVolume?.(volumeId);
  const imageId = imageVolume?.imageIds?.[0];
  if (!imageId) return null;
  const voiLutModule = metaData.get("voiLutModule", imageId);
  const rawCenter = Array.isArray(voiLutModule?.windowCenter)
    ? voiLutModule.windowCenter[0]
    : voiLutModule?.windowCenter;
  const center = Number(rawCenter);
  return center;
}

export default function setPetColorMapTransferFunctionForVolumeActor({
  volumeActor,
  volumeId,
  preset,
}) {
  const mapper = volumeActor.getMapper?.();
  if (mapper?.setSampleDistance) {
    mapper.setSampleDistance(1.0);
  }

  const cfun = vtkColorTransferFunction.newInstance();
  const presetToUse = preset || getColormap("siemens");
  cfun.applyColorMap(presetToUse);

  const center = getWindowCenterFromVolumeId(volumeId);
  const upper = center > 1 ? center : 5;
  const safeUpper = Number.isFinite(upper) && upper > 0 ? upper : 5;
  const rangeMin = 0;
  const rangeMax = safeUpper;
  cfun.setScale(Scale.LOG10);
  cfun.setMappingRange(rangeMin, rangeMax);

  volumeActor.getProperty().setRGBTransferFunction(0, cfun);
  //低信号更明显，系数可以更小
  const thresholdValue0 = Math.max(rangeMin, rangeMax * 0.002);
  const thresholdValue1 = Math.max(thresholdValue0, rangeMax * 0.02);
  const delta = Math.abs(rangeMax - rangeMin) * 0.001;
  const threshold0MinusDelta = Math.max(rangeMin, thresholdValue0 - delta);

  const ofun = vtkPiecewiseFunction.newInstance();
  ofun.addPoint(rangeMin, 0.0);
  ofun.addPoint(threshold0MinusDelta, 0.0);
  //低信号更明显，系数可以更小
  ofun.addPoint(thresholdValue0, 0.08);
  ofun.addPoint(thresholdValue1, 0.9);
  ofun.addPoint(rangeMax, 1.0);
  volumeActor.getProperty().setScalarOpacity(0, ofun);
} 
