import superagentPromise from 'superagent-promise';
import _superagent from 'superagent';
import promise from 'promise'
const superagent = superagentPromise(_superagent, promise);

const handleErrors = err => {
  if (err && err.response && err.response.status === 401) {
    // login out ?
  }
  return err;
};

const responseBody = (res, backParams) => {
  if(backParams) {
    return {...res.body, backParams} || {...JSON.parse(res.text), backParams}
  }else{
    return res.body || JSON.parse(res.text)
  }
};

const tokenPlugin = (req, token, header) => {
  req.set('authorization', `bearer ${token}`);
  if(header) {
    for(const key in header) {
      req.set(key, header[key]);
    }
  }
};

const getUrl = (apiRoot, url, apiVersion, version) => {
  return `${apiRoot}/${version ? version : apiVersion}${url}`
}

const requests = (token, apiRoot, apiVersion) => {
  return {
    get: (url, backParams, version, header) =>
      superagent
        .get(getUrl(apiRoot, url, apiVersion, version))
        .use((req) => {
          tokenPlugin(req, token, header)
        })
        .end(handleErrors)
        .then(res =>responseBody(res,backParams)),
    post: (url, body, backParams, version, header) =>
      superagent
        .post(getUrl(apiRoot, url, apiVersion, version), body)
        .use((req) => {
          tokenPlugin(req, token, header)
        })
        .end(handleErrors)
        .then(res =>responseBody(res,backParams)),
  }
};

export default requests
