import dicomParser from 'dicom-parser'
import * as cornerstone3D from '@cornerstonejs/core'
import * as cornerstone3DTools from '@cornerstonejs/tools'
import cornerstoneDICOMImageLoader from '@cornerstonejs/dicom-image-loader'

window.cornerstone3D = cornerstone3D
window.cornerstone3DTools = cornerstone3DTools
const { preferSizeOverAccuracy, useNorm16Texture } =
cornerstone3D.getConfiguration().rendering

export default function initCornerstoneDICOMImageLoader() {
  cornerstoneDICOMImageLoader.external.cornerstone = cornerstone3D
  cornerstoneDICOMImageLoader.external.dicomParser = dicomParser
  cornerstoneDICOMImageLoader.configure({
    useWebWorkers: false,
    decodeConfig: {
      convertFloatPixelDataToInt: false,
      use16BitDataType: preferSizeOverAccuracy || useNorm16Texture
    }
  })

  let maxWebWorkers = 1

  if (navigator.hardwareConcurrency) {
    maxWebWorkers = Math.min(navigator.hardwareConcurrency, 7)
  }

  var config = {
    maxWebWorkers,
    startWebWorkersOnDemand: false,
    taskConfiguration: {
      decodeTask: {
        initializeCodecsOnStartup: false,
        strict: false
      }
    }
  }

  cornerstoneDICOMImageLoader.webWorkerManager.initialize(config)
}
