/* global XMLHttpRequest, Image */

let imgCache = {}

// Find the assets directory properly
function fixURI (path, a = '') {
  let pn = window.location.pathname
  if (path.indexOf('/assets') === -1) path = '/assets/' + a + path
  if (pn === '/' || pn === '/index.html') return path
  let assetsDir = pn + path
  return assetsDir.replace(/\/\//g, '/')
}

function GET (url, istext) {
  return new Promise((resolve, reject) => {
    var xmlHttp = new XMLHttpRequest()

    xmlHttp.onreadystatechange = function () {
      if (xmlHttp.readyState === 4 && xmlHttp.status === 200) {
        resolve(xmlHttp.responseText)
      } else if (xmlHttp.readyState === 4 && xmlHttp.status >= 400) {
        let err = new Error(xmlHttp.status)
        err.request = xmlHttp
        reject(err)
      }
    }

    xmlHttp.open('GET', fixURI(url), true)
    istext && (xmlHttp.responseType = 'text')
    xmlHttp.send(null)
  })
}

function smartGET (data) {
  if (typeof data === 'string') {
    data = {
      url: data,
      type: 'text'
    }
  }

  if (!data.type) data.type = 'text'
  let istext = (data.type !== 'image' && data.type !== 'file')

  let url = data.url
  if (!url) throw new Error('URL is required!')

  if (data.type === 'json') {
    return new Promise((resolve, reject) => {
      GET(url).then((dtext) => {
        try {
          let jsonp = JSON.parse(dtext)
          return resolve(jsonp)
        } catch (e) {
          reject(e)
        }
      }, reject)
    })
  }

  return GET(data.url, istext)
}

function loadImage (url) {
  url = fixURI(url, 'textures/')

  // Ensure we don't load a texture multiple times
  if (imgCache[url]) return imgCache[url]

  return new Promise((resolve, reject) => {
    let img = new Image()

    img.onload = function () {
      imgCache[url] = img
      resolve(img)
    }

    img.onerror = function (e) {
      reject(e)
    }

    img.src = url
  })
}

function imageToSampler (img) {
  let canvas = document.createElement('canvas')
  let ctx = canvas.getContext('2d')
  canvas.width = img.width
  canvas.height = img.height
  ctx.drawImage(img, 0, 0, img.width, img.height)
  return function (x, y) {
    return ctx.getImageData(x, y, 1, 1).data
  }
}

export default { GET: smartGET, imageToSampler, loadImage }
