export default {
  imageHasData (img) {
    return !!(img.exifdata)
  },
  getStringFromDB (buffer, start, length) {
    var outstr = ''
    for (var n = start; n < start + length; n++) {
      outstr += String.fromCharCode(buffer.getUint8(n))
    }
    return outstr
  },
  xml2Object (xml) {
    var obj = {}
    if (xml.childNodes.length > 0) {
      for (var i = 0; i < xml.childNodes.length; i++) {
        var item = xml.childNodes[i]
        var attributes = item.attributes
        for (var idx in attributes) {
          var itemAtt = attributes[idx]
          var dataKey = itemAtt.nodeName
          var dataValue = itemAtt.nodeValue

          if (dataKey !== undefined) {
            obj[dataKey] = dataValue
          }
        }
        var nodeName = item.nodeName

        if (obj[nodeName] == null || typeof (obj[nodeName]) == 'undefined') {
          obj[nodeName] = this.xml2json(item)
        } else {
          if (typeof (obj[nodeName].push) == 'undefined') {
            var old = obj[nodeName]

            obj[nodeName] = []
            obj[nodeName].push(old)
          }
          obj[nodeName].push(this.xml2json(item))
        }
      }
    } else {
      obj = xml.textContent
    }
    return obj
  },
  xml2json (xml) {
    var json = {}

    if (xml.nodeType == 1) { // element node
      if (xml.attributes.length > 0) {
        json['@attributes'] = {}
        for (var j = 0; j < xml.attributes.length; j++) {
          var attribute = xml.attributes.item(j)
          json['@attributes'][attribute.nodeName] = attribute.nodeValue
        }
      }
    } else if (xml.nodeType == 3) { // text node
      return xml.nodeValue
    }

    // deal with children
    if (xml.hasChildNodes()) {
      for (var i = 0; i < xml.childNodes.length; i++) {
        var child = xml.childNodes.item(i)
        var nodeName = child.nodeName
        if (json[nodeName] == null) {
          json[nodeName] = this.xml2json(child)
        } else {
          if (json[nodeName].push == null) {
            var old = json[nodeName]
            json[nodeName] = []
            json[nodeName].push(old)
          }
          json[nodeName].push(this.xml2json(child))
        }
      }
    }

    return json
  },
  objectURLToBlob (url, callback) {
    var http = new XMLHttpRequest()
    http.open('GET', url, true)
    http.responseType = 'blob'
    http.onload = function () {
      if (this.status == 200 || this.status === 0) {
        callback(this.response)
      }
    }
    http.send()
  },
  base64ToArrayBuffer (base64) {
    base64 = base64.replace(/^data:([^;]+);base64,/gmi, '')
    var binary = atob(base64)
    var len = binary.length
    var buffer = new ArrayBuffer(len)
    var view = new Uint8Array(buffer)
    for (var i = 0; i < len; i++) {
      view[i] = binary.charCodeAt(i)
    }
    return buffer
  }
}