import axios from "axios";
import * as types from "../actionTypes/actionTypes"

export const editEvent = payload => {
	return {
		type: types.EDIT_EVENT,
		payload
	};
};

//POST
const postNewEventRequest = payload => ({
	type: types.POST_NEW_EVENT_REQUEST,
	payload
});
const postNewEventRequestSuccess = payload => ({
	type: types.POST_NEW_EVENT_REQUEST_SUCCESS,
	payload
});
const postNewEventRequestFail = payload => ({
	type: types.POST_NEW_EVENT_REQUEST_FAIL,
	payload
});

export const postNewEvent = payload => {
	return async dispatch => {
		dispatch(postNewEventRequest());
		try {
			const { data } = await axios.post("https://api-marathon.herokuapp.com/api/v1/event", payload);
			dispatch(postNewEventRequestSuccess(data));
			console.log("New Event Posted", payload)
		} catch (error) {
			dispatch(postNewEventRequestFail(error));
		}
	};
};

//GET
const getEventsRequest = payload => ({
	type: types.GET_EVENTS_REQUEST,
	payload
});

const getEventsRequestSuccess = payload => ({
	type: types.GET_EVENTS_REQUEST_SUCCESS,
	payload
});

const getEventsRequestFail = payload => ({
	type: types.GET_EVENTS_REQUEST_FAIL,
	payload
});

export const getEvents = () => dispatch => {
	dispatch(getEventsRequest());
	return axios
		.get("https://api-marathon.herokuapp.com/api/v1/event")
		.then(res => dispatch(getEventsRequestSuccess(res)))
		.catch(err => dispatch(getEventsRequestFail(err)));
};

// REMOVE
const removeEventRequest = payload => ({
	type: types.REMOVE_EVENT_REQUEST,
	payload
});

const removeEventSuccess = payload => ({
	type: types.REMOVE_EVENT_REQUEST_SUCCESS,
	payload
});

const removeEventFail = payload => ({
	type: types.REMOVE_EVENT_REQUEST_FAIL,
	payload
});

export const removePost = id => dispatch => {
	dispatch(removeEventRequest());
	return axios
		.delete(`https://api-marathon.herokuapp.com/api/v1/event/:${id}`)
		.then(res => dispatch(removeEventSuccess({ res, id })))
		.catch(err => dispatch(removeEventFail(err)));
};