import axios from "axios";
import NewsSingleWP from "../models/NewsSingleWP";
import CategoryWP from "../models/CateroryWP";
import {onRequestFulfilled, onResponseRejected} from "./axios";


const baseurl = "http://egov.demokritos-dev.eu/wp-json/wp/v2";
const postsEndpoint = "/posts";


const categoriesEndpoint = "/categories";



export const instance = axios.create({
	timeout: 15000,
	baseURL: baseurl,
});



instance.interceptors.request.use(
	onRequestFulfilled
);



/**
 * Global Error handling
 * Errors are returned so they can more specifically handled where they are called?
 */
instance.interceptors.response.use(
	function (response) {
		// Any status code that lie within the range of 2xx cause this function to trigger
		// Do something with response data
		return response;
	},
	onResponseRejected
);

export function getPostsWP(currentPage: number,
						   currentOrder: string,
						   currentCategory: string,) {
	return instance.get<NewsSingleWP[]>(postsEndpoint, {
		params: {
			per_page: 3,
			page: currentPage,
			order: currentOrder,
			//by default we want all posts so, current category parameterer must be optional (it only gets defined if and when filtering is on)
			...(currentCategory ? { categories: currentCategory } : {}),
		}
	});
}

export function getCategoriesWP() {
	return instance.get<CategoryWP[]>(categoriesEndpoint);
}

//
// export const getPostsWP = (
// 	currentPage: number,
// 	currentOrder: string,
// 	currentCategory: string,
// ) => {
// 	return axios<NewsSingleWP>({
// 		method: "get",
// 		baseURL: baseurl,
// 		url: postsEndpoint,
// 		params: {
// 			per_page: 3,
// 			page: currentPage,
// 			order: currentOrder,
// 			//by default we want all posts so, current category parameterer must be optional (it only gets defined if and when filtering is on)
// 			...(currentCategory ? { categories: currentCategory } : {}),
// 		},
// 	})
// 		.then(function (response) {
// 			return response;
// 		})
// 		.catch(function (error) {
//
// 			return error;
// 		});
// };
//
// export const getCategoriesWP = () => {
// 	return axios<CategoryWP>({
// 		method: "get",
// 		baseURL: baseurl,
// 		url: categoriesEndpoint,
// 	})
// 		.then(function (response) {
// 			return response;
// 		})
// 		.catch(function (error) {
//
// 			return error;
// 		});
// };
