import dicomParser from "dicom-parser";
import dcmjs from 'dcmjs'
const CharLs = require('@cornerstonejs/codec-charls')
const codecWrapper = {
  codec: undefined,
  Decoder: undefined,
  Encoder: undefined,
  encoderName: "JpegLSEncoder",
  decoderName: "JpegLSDecoder",
};
function setCodec(codecConfig, encoderName, decoderName, codec = {}) {
  codecConfig.Encoder = codec[encoderName];
  codecConfig.Decoder = codec[decoderName];
  codecConfig.codec = codec;
}
CharLs().then(res => {
  setCodec(codecWrapper, codecWrapper.encoderName, codecWrapper.decoderName, res);
})

export const encoder = function (file) {
  return new Promise(async (resolve, reject) => {
    try {
      const reader = new FileReader()
      reader.onload = async (event) => {
        let buffer = event.target.result
        let data = dicomParser.parseDicom(new Uint8Array(buffer))
        let frameCount = data.string('x00280008')
        let height = data.uint16('x00280011')
        let width = data.uint16('x00280010')
        let bitsPerSample = data.uint16('x00280100')
        let componentCount = data.string('x00280004')
        let transportSyntax = data.string('x00020010')
        let dataset = dcmjs.data.DicomMessage.readFile(buffer)
        let pixelDataElement = data.elements.x7fe00010
        let pixelDataOffset = pixelDataElement.dataOffset
        let pixelDataLength = pixelDataElement.length
        let pixelDataBytes = data.byteArray.subarray(pixelDataOffset, pixelDataOffset + pixelDataLength)
        if ((transportSyntax === '1.2.840.10008.1.2.1' || transportSyntax === '1.2.840.10008.1.2') && ~componentCount.indexOf('MONOCHROME') && !frameCount) {
          let encoder = new codecWrapper.Encoder()
          let decodedBytes = encoder.getDecodedBuffer({width: width, height: height, bitsPerSample: bitsPerSample, componentCount: 1})
          encoder.setNearLossless(0)
          decodedBytes.set(pixelDataBytes)
          encoder.encode()
          let encodedBytes = encoder.getEncodedBuffer();
          dataset.dict['7FE00010'].Value[0] = encodedBytes.buffer
          dataset.meta['00020010'].Value[0] = '1.2.840.10008.1.2.4.80'
          let newDicomFile = dataset.write()
          const bufferArray = new Uint8Array(newDicomFile)
          const blob = new Blob([bufferArray], { type: 'application/octet-stream' })
          resolve({blob, data})
        } else {
          const bufferArray = new Uint8Array(buffer);
          const blob = new Blob([bufferArray], { type: 'application/octet-stream' });
          resolve({blob, pixelDataBytes})
        }
      };
      reader.readAsArrayBuffer(file);
    } catch (e) {
      console.log(e)
      reject(e)
    }
  })
}
