/* eslint-disable no-unused-vars */
import dcmjs from 'dcmjs'
import { calculateSUVScalingFactors } from '@cornerstonejs/calculate-suv'
import { getPTImageIdInstanceMetadata } from './getPTImageIdInstanceMetadata'
import { utilities } from '@cornerstonejs/core'
import { wadouri } from '@cornerstonejs/dicom-image-loader'
import ptScalingMetaDataProvider from './ptScalingMetaDataProvider'
import getPixelSpacingInformation from './getPixelSpacingInformation'
import { convertMultiframeImageIds, prefetchMetadataInformation } from './convertMultiframeImageIds'
import removeInvalidTags from './removeInvalidTags'
const { calibratedPixelSpacingMetadataProvider } = utilities
function parseImageId(imageId) {
  // build a url by parsing out the url scheme and frame index from the imageId
  const firstColonIndex = imageId.indexOf(':')

  let url = imageId.substring(firstColonIndex + 1)
  const frameIndex = url.indexOf('frame=')

  let frame

  if (frameIndex !== -1) {
    const frameStr = url.substr(frameIndex + 6)

    frame = parseInt(frameStr, 10)
    url = url.substr(0, frameIndex - 1)
  }

  return {
    scheme: imageId.substr(0, firstColonIndex),
    url,
    frame
  }
}
async function createImageIdsAndCacheMetaData({
  modality,
  imageIds
}) {
  await prefetchMetadataInformation(imageIds)
  imageIds = convertMultiframeImageIds(imageIds)
  imageIds.forEach((imageId) => {
    const parseImage = parseImageId(imageId)
    const imageData =
    wadouri.dataSetCacheManager.get(parseImage.url)
    const arrayBuffer = imageData.byteArray.buffer
    var dicomData = dcmjs.data.DicomMessage.readFile(arrayBuffer)
    var dataset = dcmjs.data.DicomMetaDictionary.naturalizeDataset(
      dicomData.dict
    )
    dataset._meta = dcmjs.data.DicomMetaDictionary.namifyDataset(
      dicomData.meta
    )
    var instanceMetaData = dataset
    instanceMetaData = removeInvalidTags(instanceMetaData)
    if (instanceMetaData) {
      const pixelSpacing = getPixelSpacingInformation(instanceMetaData)
      if (pixelSpacing) {
        calibratedPixelSpacingMetadataProvider.add(
          imageId,
          // pixelSpacing.map((s) => parseFloat(s))
          { rowPixelSpacing: parseFloat(pixelSpacing[0]),
            columnPixelSpacing: parseFloat(pixelSpacing[1])
          }
        )
      }
    }
  })
  if (modality === 'PT') {
    const InstanceMetadataArray = []
    imageIds.forEach((imageId) => {
      // var parseImage = parseImageId(imageId)
      // imageId,
      const instanceMetadata = getPTImageIdInstanceMetadata(imageId)
      if (typeof instanceMetadata.CorrectedImage === 'string') {
        instanceMetadata.CorrectedImage =
          instanceMetadata.CorrectedImage.split('\\')
      }

      if (instanceMetadata) {
        InstanceMetadataArray.push(instanceMetadata)
      }
    })
    if (InstanceMetadataArray.length) {
      // const suvScalingFactors = calculateSUVScalingFactors(
      //   InstanceMetadataArray
      // )
      // InstanceMetadataArray.forEach((instanceMetadata, index) => {
      //   ptScalingMetaDataProvider.addInstance(
      //     imageIds[index],
      //     suvScalingFactors[index]
      //   )
      // })
      try {
        const suvScalingFactors = calculateSUVScalingFactors(
          InstanceMetadataArray
        )
        InstanceMetadataArray.forEach((instanceMetadata, index) => {
          ptScalingMetaDataProvider.addInstance(
            imageIds[index],
            suvScalingFactors[index]
          )
        })
      } catch (error) {
        console.log(error)
      }
    }
  }
  return imageIds
}

export { createImageIdsAndCacheMetaData }
