/**
 * Created by radko on 13.06.17.
 */

import Axios from 'axios'
import { stringify } from 'qs'
import { Vapi } from 'vuex-rest-api'
import localAuth from '../localAuth'

export default class VapiWrapper {
  constructor(baseURL = null, options = {}) {
    options.baseURL = baseURL

    options.axios = Axios.create({
      paramsSerializer: function ({filter, fields, limit, page, sort, include}) {
        return stringify(
          {filter, fields, limit, page, sort, include},
          {arrayFormat: 'indices'}
        )
      }
    })

    options.axios.interceptors.request.use(
      (config) => {
        config.headers.common['Accept'] = 'application/json'
        config.headers.common['Content-Type'] = 'application/json'
        config.headers.common['Access-Control-Allow-Origin'] = '*'

        if (localAuth.jePouzivatelAutentifikovany()) {
          config.headers.common['Authorization'] = 'Bearer ' + localAuth.apiToken()
        }

        return config
      },
      (response) => {
        return response
      }
    )

    options.queryParams = true

    return new Vapi(options)
  }
}
