import { utilities as csUtils } from '@cornerstonejs/core'

const scalingPerImageId = {}

function normalizeImageURI(imageURI) {
  if (!imageURI) return imageURI
  const qIndex = imageURI.indexOf('?')
  if (qIndex === -1) return imageURI
  const base = imageURI.slice(0, qIndex)
  const query = imageURI.slice(qIndex + 1)
  const params = new URLSearchParams(query)
  if (!params.has('frame')) return imageURI
  params.delete('frame')
  const rest = params.toString()
  return rest ? `${base}?${rest}` : base
}

function addInstance(imageId, scalingMetaData) {
  // 统一缩放元数据的 key：忽略 frame 参数，避免 getCurrentImageId() 带 frame 导致查不到 scalingModule
  const imageURI = normalizeImageURI(csUtils.imageIdToURI(imageId))
  scalingPerImageId[imageURI] = scalingMetaData
}

function get(type, imageId) {
  if (type === 'scalingModule') {
    const imageURI = normalizeImageURI(csUtils.imageIdToURI(imageId))
    return scalingPerImageId[imageURI]
  }
}

export default { addInstance, get }
