import axios from 'axios'
import axiosRetry from "axios-retry";

import config from "../../config";

console.log(config);
const baseUrl = config.backendBaseUrl ? config.backendBaseUrl : `${window.location.origin}/api/v1`;

const client = axios.create({
  // headers: {},
  baseURL: baseUrl,
  timeout: 8000,
  withCredentials: true
})

axiosRetry(client, {
  retries: 3,
  shouldResetTimeout: true
})

/**
 *
 * @param response {{
 *   code: number,
 *   msg: string,
 *   data: any
 * }}
 * @returns {*}
 * @throws {{code: number, message: string}}
 */
function processResponse(response) {
  const json = response.data
  if (json.code !== 0) {
    throw {
      code: json.code, message: json.msg ? json.msg : JSON.stringify(json)
    }
  }

  return json.data
}

const filenameRegex = /filename[^;=\n]*="((['"]).*?\2|[^;\n]*)"/;

function processFileDL(response) {
  let data = response.data

  if (response.headers.getContentType() !== 'application/octet-stream' || !data) {
    return processResponse(response)
  }

  const matches = filenameRegex.exec(response.headers.get('content-disposition'));

  response.headers.get('Content-Disposition')

  const a = document.createElement('a')
  a.style.display = 'none'
  a.href = window.URL.createObjectURL(new Blob([data]))
  a.target = "_blank"
  a.setAttribute('download', decodeURI(matches[1]))
  document.body.appendChild(a)
  a.click()
  window.URL.revokeObjectURL(a.href)
  document.body.removeChild(a)

  return undefined
}

export {
  client, processResponse, processFileDL
}
