import dicomParser from "dicom-parser";
import dcmjs from 'dcmjs'

export const anonymization = function (file, config) {
  return new Promise(async (resolve, reject) => {
    try {
      const reader = new FileReader()
      let AnonymizeFixedList = config.AnonymizeFixedList
      let AnonymizeNotFixedList = config.AnonymizeNotFixedList
      let DicomStoreInfo = config.DicomStoreInfo
      reader.onload = async (event) => {
        let buffer = event.target.result
        let data = dicomParser.parseDicom(new Uint8Array(buffer))
        let dataset = dcmjs.data.DicomMessage.readFile(buffer)
        console.log(dataset.dict)
        for (var i = 0; i < AnonymizeFixedList.length; i++) {
          let AnonymizeFixed = AnonymizeFixedList[i]
          if (dataset.dict[AnonymizeFixed.Group + AnonymizeFixed.Element]) {
            dataset.dict[AnonymizeFixed.Group + AnonymizeFixed.Element].Value[0] = AnonymizeFixed.ReplaceValue
          } else {
            dataset.dict[AnonymizeFixed.Group + AnonymizeFixed.Element] = {
              vr: AnonymizeFixed.ValueRepresentation,
              Value: [
                AnonymizeFixed.ReplaceValue
              ]
            }
          }
        }
        for (var i = 0; i < AnonymizeNotFixedList.length; i++) {
          let AnonymizeNotFixed = AnonymizeNotFixedList[i]
          if (dataset.dict[AnonymizeNotFixed.Group + AnonymizeNotFixed.Element]) {
            dataset.dict[AnonymizeNotFixed.Group + AnonymizeNotFixed.Element].Value[0] = DicomStoreInfo[AnonymizeNotFixed.ReplaceValue] ? DicomStoreInfo[AnonymizeNotFixed.ReplaceValue].toString() : ''
          } else {
            dataset.dict[AnonymizeNotFixed.Group + AnonymizeNotFixed.Element] = {
              vr: AnonymizeNotFixed.ValueRepresentation,
              Value: [
                DicomStoreInfo[AnonymizeNotFixed.ReplaceValue]
              ]
            }
          }
        }
        let newDicomFile = dataset.write()
        const bufferArray = new Uint8Array(newDicomFile)
        const blob = new Blob([bufferArray], { type: 'application/octet-stream' })
        resolve({blob, data})
      };
      reader.readAsArrayBuffer(file);
    } catch (e) {
      console.log(e)
      reject(e)
    }
  })
}
