import axios from 'axios'

let links

// do not prefix route with basepath, ex. for external links
const addBasepath = (url, excludeBasepath) => {
  const basepath = window.basepath || ''

  return excludeBasepath ? url : `${basepath}${url}`
}

const generateResponseWithLinks = (
  response,
  {auth, logout, external, custom}
) => ({
  ...response,
  auth: {links: auth},
  logoutLink: logout,
  external,
  custom,
})

const AJAX = async (
  {url, resource, id, method = 'GET', data = {}, params = {}, headers = {}},
  excludeBasepath
) => {
  try {
    let response

    url = addBasepath(url, excludeBasepath)

    if (!links) {
      const linksRes = (response = await axios({
        url: addBasepath('/chronograf/v1', excludeBasepath),
        method: 'GET',
      }))
      links = linksRes.data
    }

    if (resource) {
      url = id
        ? addBasepath(`${links[resource]}/${id}`, excludeBasepath)
        : addBasepath(`${links[resource]}`, excludeBasepath)
    }

    response = await axios({
      url,
      method,
      data,
      params,
      headers,
    })

    return generateResponseWithLinks(response, links)
  } catch (error) {
    const {response} = error

    throw generateResponseWithLinks(response, links) // eslint-disable-line no-throw-literal
  }
}

export const get = async url => {
  try {
    return await AJAX({
      method: 'GET',
      url,
    })
  } catch (error) {
    console.error(error)
    throw error
  }
}

export default AJAX

@@ -273,19 +273,16 @@
 inks = (
-%0A  
 response
@@ -282,18 +282,16 @@
 esponse,
-%0A 
  %7Bauth, 
@@ -310,18 +310,9 @@
 rnal
-, custom%7D%0A
+%7D
 ) =%3E
@@ -391,18 +391,8 @@
 al,%0A
-  custom,%0A
 %7D)%0A%0A

Remove unused redux key from ajax links response