import axios from 'axios';
import { ApiError } from './index';
export class APIBase {
  constructor(endpoint, defaultHeaders = {}) {
    this.headers = {};
    this.addAuthInterceptor = (accessToken, sessionToken) => {
      this.axios.interceptors.request.use((config) => {
        config.headers.Authorization = `Bearer ${accessToken}`;
        if (sessionToken)
          config.headers['Session-Token'] = sessionToken;
        return config;
      });
    };
    this.axios = axios.create({
      baseURL: endpoint,
      headers: Object.assign({ 'Accept': 'application/json', 'Content-Type': 'application/json' }, defaultHeaders),
    });
  }
  getDefaults() {
    return this.axios.defaults;
  }
  post(url, body) {
    return this.send('post', `/${url}`, { body });
  }
  put(url, body) {
    return this.send('put', `/${url}`, { body });
  }
  delete(url) {
    return this.send('delete', `/${url}`);
  }
  get(url, params, headers) {
    return this.send('get', `/${url}`, { headers, params });
  }
  send(method, url, options) {
    return new Promise((resolve, reject) => {
      this.axios.request({
        data: options.body,
        headers: Object.assign(Object.assign({}, this.headers), (options.headers)),
        method,
        params: options.params,
        url,
      }).then((response => {
        resolve(response.data);
      })).catch((error) => {
        if (error.response) {
          // The request was made and the server responded with a status code
          // that falls out of the range of 2xx
          reject(ApiError.decode(error.response));
        }
        else if (error.request) {
          // The request was made but no response was received
          // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
          // http.ClientRequest in node.js
          reject(new ApiError('network'));
        }
        else {
          // Something happened in setting up the request that triggered an Error
          reject(new ApiError('client'));
        }
      });
    });
  }
}
