//This worker will be used for cryptographic, long running and API calls
//to keep the UI free

import Api from './api.js'

const name = 'main'

// TODO
//if (window.isSecureContext) {
  //// Page is a secure context so service workers are now available
  //navigator.serviceWorker.register("/offline-worker.js").then(function () {
    //...
  //});
//}

function hexString(buffer) {
      const byteArray = new Uint8Array(buffer);

      const hexCodes = [...byteArray].map(value => {
              const hexCode = value.toString(16);
              const paddedHexCode = hexCode.padStart(2, '0');
              return paddedHexCode;
            });

      return hexCodes.join('');
}

async function getSHA256(file){

    // Read as array buffer
    let fileReader = new FileReaderSync();
    let buffer = fileReader.readAsArrayBuffer(file);

    // Return hex encoded sha256
     return crypto.subtle.digest('SHA-256', buffer)
        .then(v => { return hexString(v) })

}

async function newUpload(files, options){
    let filesMetadata = await Promise.all(files.map(async (f) => {
        return {
            lastModified: f.lastModified,
            type: f.type,
            name: f.name,
            size: f.size,
            sha256: await getSHA256(f)
        }
    }))

    // Get sha256
    //for (let file of files) {
    //    let sha256 = getSHA256(file)
    //    file.sha256 = sha256
    //    console.log(files)

    //}

    let upload = new Api.Upload(filesMetadata, files, options)

    // Ask permission to send a new upload
     await upload.create()
     .then(data => {
         // Get the upload id
        //let { result: {
            //upload_id: id,
            //invoice: invoice ,
            //status: status
        //} } = data;

         // Notify the UI
         console.log('notifying')
         console.log(Object.assign({msg: 'upload-invoice'}, data) )
        postMessage( Object.assign({msg: 'upload-invoice'}, data) )
        return data

     })
    .catch((e)=>{console.error('could not start upload ', e)})

     // send the files
     await upload.send()
     .then(resp =>{
         console.log('storage done')
         console.log(resp);
     })
     .catch(err =>{
         console.error(err)
     })


}

self.onmessage = e => {

    switch (e.data.msg) {
        case 'init':
            console.log(`initialized ${name} worker`);
            break;

        case 'file-sha256':
            getSHA256(e.data.payload)
            break;

        case 'new-upload':
            let { files, options } = e.data.payload;
            newUpload(files, options)
            break;

        case 'watch-payment':
            console.log('worker watching payment ' + e.data.uploadId);
            Api.pollUploadStatus(e.data.uploadId)
                .then((data)=>{

                    self.postMessage(Object.assign({msg: 'payment-received'}, data))

                    console.log('payment status update !')
                    console.log(data)
                })
            break;


        default:
            console.log(`${name} worker: need {msg: "message type", ... }`)
            break;

    }

}
