import { f7 } from 'framework7-vue'

export default {
  methods: {
    newUid (length) {
      const uidLength = length || 16
      const uidChars = 'abcdefghijklmnopqrstuvwxyz0123456789'
      var uid = []
      for (var i = 0; i < uidLength; i++) {
        uid.push(uidChars.charAt(Math.floor(Math.random() * ((i < 4) ? 26 : 36))))
      }
      return uid.join('')
    },
    uploadData (imagePayload, classPayload, prevUid) {
      let uploadImage = new Promise (resolve => {
        const dataUid = prevUid || this.newUid(16)
        var byteChars = window.atob(imagePayload)
        var byteArrays = []
        var len = byteChars.length
    
        for (var offset = 0; offset < len; offset += 1024) {
          var slice = byteChars.slice(offset, offset + 1024)
          var byteNumbers = new Array(slice.length)
          for (var i = 0; i < slice.length; i++) {
            byteNumbers[i] = slice.charCodeAt(i)
          }

          var byteArray = new Uint8Array(byteNumbers)
          byteArrays.push(byteArray)
        }  
        var imageBlob = new Blob(byteArrays, {type: 'image/jpeg'})   

        var xhrJpg = new XMLHttpRequest()
        var uploadUrl = `https://nextcloud.azgeorgis.net/public.php/webdav/${dataUid}.jpeg`
        xhrJpg.open("PUT", uploadUrl)
        xhrJpg.setRequestHeader('Content-Type', 'image/jpeg')
        xhrJpg.setRequestHeader('X-Method-Override', 'PUT')
        xhrJpg.setRequestHeader('X-Requested-With', 'XMLHttpRequest')
        xhrJpg.setRequestHeader("Authorization", "Basic " + btoa("LKBm3H6JdSaywyg:"))
        xhrJpg.send(imageBlob)

        var xhrTxt = new XMLHttpRequest()
        var uploadUrl = `https://nextcloud.azgeorgis.net/public.php/webdav/${dataUid}.txt`
        xhrTxt.open("PUT", uploadUrl)
        xhrTxt.setRequestHeader('Content-Type', 'text/plain')
        xhrTxt.setRequestHeader('X-Method-Override', 'PUT')
        xhrTxt.setRequestHeader('X-Requested-With', 'XMLHttpRequest')
        xhrTxt.setRequestHeader("Authorization", "Basic " + btoa("LKBm3H6JdSaywyg:"))
        xhrTxt.send(JSON.stringify(classPayload))

        resolve(dataUid)
      })
      return uploadImage.then((newUid) => {
        var toast = f7.toast.create({
          text: 'Detections Uploaded: thank you.',
          closeTimeout: 2000
        })
        toast.open()
        return newUid
      }).catch((e) => {
        console.log(e.message)
        f7.dialog.alert(`Error uploading image: ${e.message}`)
        return null
      })
    }
  }
}