/**
 * Class with a collection of static functions for performing various api calls.
 */
class ApiUtil {

  /**
   * Provided a URL this will perform a GET via XMlHttpRequest and returns a Promise object where you can put callbacks
   * to indicate how to handle the data.
   */
  static get (url) {
    return new Promise(function (resolve, reject) {
      var req = new XMLHttpRequest()
      req.open('GET', url)
      req.onload = function () {
        // This is called even on 404 etc
        // so check the status
        if (req.status === 200) {
          // Resolve the promise with the response text
          resolve(req.response)
        } else {
          // Otherwise reject with the status text
          // which will hopefully be a meaningful error
          reject(Error(req.status))
        }
      }
      // Handle network errors
      req.onerror = function () {
        reject(Error(`Could not fetch: '${url}'`))
      }
      // Make the request
      req.send()
    })
  }

  /**
   * Provided a URL this will perform a POST via XMlHttpRequest and returns a Promise object where you can put callbacks
   * to indicate how to handle the data.
   */
  static post (url, json) {
    return new Promise(function (resolve, reject) {
      var req = new XMLHttpRequest()
      req.open('POST', url)
      // req.setRequestHeader('Content-Type', 'application/json')
      req.onload = function () {
        // This is called even on 404 etc
        // so check the status
        if (req.status === 200) {
          // Resolve the promise with the response text
          resolve(req.response)
        } else {
          // Otherwise reject with the status text
          // which will hopefully be a meaningful error
          reject(Error(req.response))
        }
      }
      // Handle network errors
      req.onerror = function () {
        reject(Error(`Could not post: '${url}'`))
      }
      // Make the request
      req.send(json)
    })
  }

  /**
   * Provided a URL this will call get() on it and parse the response into a .json.
   */
  static getJson (url) {
    console.log(url)
    return ApiUtil.get(url).then(JSON.parse)
  }

  /**
   * Querys our API for a list of metrics.
   */
  static getMetrics () {
    let url = ApiUtil.urlPrefix + 'metrics'
    return ApiUtil.getJson(url)
  }

  /**
   * Queries our API for a list of projects.
   */
  static getProjects () {
    let url = ApiUtil.urlPrefix + 'projects'
    return ApiUtil.getJson(url)
  }

  /**
   * Queries our API for a list of orgs.
   */
  static getOrgs () {
    let url = ApiUtil.urlPrefix + 'orgs'
    return ApiUtil.getJson(url)
  }

  /**
   * Queries our API for a list of teams.
   */
  static getTeams () {
    let url = ApiUtil.urlPrefix + 'teams'
    return ApiUtil.getJson(url)
  }

  /**
   * Queries our API for a list of buckets.
   */
  static getBuckets (serviceId, serviceType, metricId, startTime, endTime, bucketType) {
    let url = ApiUtil.urlPrefix + `metrics/${metricId}/${serviceType}/${serviceId}/`
    url += `${(endTime / 1000) >> 0}/${(startTime / 1000) >> 0}/${bucketType.name.toUpperCase()}`
    url += `?bucket_size=${bucketType.name.toUpperCase()}&iana_time_zone=America%2FLos_Angeles`
    return ApiUtil.getJson(url)
  }

  /**
   * Queries our API for info about a service.
   */
  static getServiceInfo (serviceId, serviceType) {
    let url = ApiUtil.urlPrefix + `${serviceType}/${serviceId}`
    return ApiUtil.getJson(url)
  }

  /**
   * Queries our API for info about a project.
   */
  static getProjectInfo (projectId) {
    let url = ApiUtil.urlPrefix + `projects/${projectId}`
    return ApiUtil.getJson(url)
  }

  /**
   * Queries our API for info about a team.
   */
  static getTeamInfo (teamId) {
    let url = ApiUtil.urlPrefix + `teams/${teamId}`
    return ApiUtil.getJson(url)
  }

  /**
   * Queries our API for info about an org.
   */
  static getOrgInfo (orgId) {
    let url = ApiUtil.urlPrefix + `orgs/${orgId}`
    return ApiUtil.getJson(url)
  }

  /**
   * Posts a project's json to the server.
   */
  static postProjectJson (json) {
    let url = ApiUtil.urlPrefix + 'projects'
    return ApiUtil.post(url, json).then(JSON.parse)
  }
}

ApiUtil.urlPrefix = '/api/v1/'

if (__DEV__) {
  ApiUtil.urlPrefix = 'http://rockpaperscissors.internal.justin.tv' + ApiUtil.urlPrefix
}

export default ApiUtil
