import axios from "axios";
import { reject } from "promise";
import { AccountController_RefreshJwtToken } from "../apiClient/routes";
import { IsJwtForRefresh, SetAuthorizationTokenLocalStorage } from "./localStorageService";

// set default URL for axios
/*axios.defaults.baseURL = config.server.apiUrl;*/
axios.defaults.baseURL = process.env.REACT_APP_API_URL;
// dunno
axios.interceptors.response.use(undefined, error => {
	const expectedError = error.response && error.response.status && error.response.status >= 400 && error.response.status < 500;

	if (!expectedError) {
		console.log("Logging the error", error);
		alert("Došlo k neočekávané chybě.");
	}

	return reject(error);
});

function setAuthorizationToken(authorizationToken: string | null) {
	if (authorizationToken !== null) {
		axios.defaults.headers.common['Authorization'] = `Bearer ${authorizationToken}`;
	}
	else {
		delete axios.defaults.headers.common["Authorization"];
	}
}

function refreshToken() {
	if (IsJwtForRefresh()) {
		axios.get<string>(AccountController_RefreshJwtToken).then(response => SetAuthorizationTokenLocalStorage(response.data));
	}
}

export default {
	get: axios.get,
	post: axios.post,
	put: axios.put,
	delete: axios.delete,
	all: axios.all,
	spread: axios.spread,
	setAuthorizationToken,
	refreshToken
}