export const LS_ACCESS_TOKEN_KEY = 'gc-comments-token'
export const LS_USER_KEY = 'gc-user-info'

export const isString = s => toString.call(s) === '[object String]'

export function getTargetContainer(container) {
  let targetContainer
  if (container instanceof Element) {
    targetContainer = container
  } else if (isString(container)) {
    targetContainer = document.getElementById(container)
  } else {
    targetContainer = document.createElement('div')
  }

  return targetContainer
}

export const Query = {
  parse(search = window.location.search) {
    if (!search) return {}
    const queryString = search[0] === '?' ? search.substring(1) : search
    const query = {}
    queryString.split('&')
      .forEach(queryStr => {
        const [key, value] = queryStr.split('=')
        if (key) query[key] = value
      })

    return query
  },
  stringify(query, prefix = '?') {
    const queryString = Object.keys(query)
      .map(key => `${key}=${encodeURIComponent(query[key] || '')}`)
      .join('&')
    return queryString ? prefix + queryString : ''
  },
}

function ajaxFactory(method) {
  return function(apiPath, data = {}, base = 'https://api.github.com') {
    const req = new XMLHttpRequest()
    const token = localStorage.getItem(LS_ACCESS_TOKEN_KEY)

    let url = `${base}${apiPath}`
    let body = null
    if (method === 'GET' || method === 'DELETE') {
      url += Query.stringify(data)
    }

    const p = new Promise((resolve, reject) => {
      req.addEventListener('load', () => {
        const data = JSON.parse(req.responseText)
        if (data.message) {
          reject(data.message)
        } else {
          resolve(data)
        }
      })
      req.addEventListener('error', error => reject(error))
    })
    req.open(method, url, true)

    req.setRequestHeader('Accept', 'application/vnd.github.squirrel-girl-preview')
    if (token) {
      req.setRequestHeader('Authorization', `token ${token}`)
    }
    if (method !== 'GET' && method !== 'DELETE') {
      body = JSON.stringify(data)
      req.setRequestHeader('Content-Type', 'application/json')
    }

    req.send(body)
    return p
  }
}

export const http = {
  get: ajaxFactory('GET'),
  post: ajaxFactory('POST'),
}

@@ -1,24 +1,20 @@
-ex
+im
 port 
-const
+%7B
  LS_ACCESS_T
@@ -26,70 +26,27 @@
 KEY 
-= 'gc-comments-token'%0Aexport const LS_USER_KEY = 'gc-user-info
+%7D from './constants
 '%0A%0Ae
@@ -1485,16 +1485,35 @@
 t data =
+ req.responseText ?
  JSON.pa
@@ -1533,16 +1533,21 @@
 nseText)
+ : %7B%7D
 %0A       
@@ -1584,16 +1584,26 @@
  reject(
+new Error(
 data.mes
@@ -1607,16 +1607,17 @@
 message)
+)
 %0A       
@@ -2209,10 +2209,70 @@
 POST'),%0A
+  delete: ajaxFactory('DELETE'),%0A  put: ajaxFactory('PUT'),%0A
 %7D%0A

add methods & fix null response parsing