import { ApiConfig } from '../config';

const axios = require('axios');

/** Set base url for api */
axios.defaults.baseURL = ApiConfig.API_URL;

/** Set common header parameters */
axios.defaults.headers.common = {
  Accept: 'application/json',
  'Content-Type': 'application/json'
};

/**
 * Set header authorization
 * @param token     Authorization token
 */
const setHeaderAuthorization = (token: any) => {
  if (token) {
    axios.defaults.headers.common.Authorization = `Bearer ${token}`;
  } else {
    axios.defaults.headers.common.Authorization = null;
  }
};

/**
 * Parse and return HTTP API response
 * @param res
 */
const getResponse = (res?: any) => {
   if (res && res.status !== 401) {

  return res.data;
   }
   throw new Error('Something went wrong');
};

/**
 * Get request
 * @param path      API url path
 * @param params    Request parameters
 */
const get = (path: string, params?: any) => {
  return new Promise((resolve, reject) => {
    try {
      axios
        .get(path, {
          params,
          validateStatus: function() {
            return true;
          }
        })
        .then(getResponse)
        .then(resolve)
        .catch(reject);
    } catch (error) {
      reject(error);
    }
  });
};

/**
 * Post request
 * @param path      API url path
 * @param params    Request parameters
 */
const post = (path: string, params?: any, headers?: any) => {
  return new Promise((resolve, reject) => {
    try {
      axios
        .post(path, params || {}, {
          headers,
          validateStatus: function() {
            return true;
          }
        })
        .then(getResponse)
        .then(resolve)
        .catch(reject);
    } catch (error) {
      reject(error);
    }
  });
};

/**
 * Put request
 * @param path      API url path
 * @param params    Request parameters
 * @param headers   Request headers
 */
const put = (path: string, params?: any, headers?: any) => {
  return new Promise((resolve, reject) => {
    try {
      axios
        .put(path, params || {}, {
          headers,
          validateStatus: function() {
            return true;
          }
        })
        .then(getResponse)
        .then(resolve)
        .catch(reject);
    } catch (error) {
      reject(error);
    }
  });
};

/**
 * Delete request
 * @param path      API url path
 * @param params    Request parameters
 */
const del = (path: string, params?: any) => {
  return new Promise((resolve, reject) => {
    try {
      axios
        .delete(path, {
          params,
          validateStatus: function() {
            return true;
          }
        })
        .then(getResponse)
        .then(resolve)
        .catch(reject);
    } catch (error) {
      reject(error);
    }
  });
};

export default { get, post, put, del, setHeaderAuthorization };
