import reduxCrud from 'lib/redux-crud';
import { fetchRequest, createRequest, updateRequest, deleteRequest } from 'lib/crud-backend';
import backendRequest from 'lib/backend';
import { settingsSelector } from 'utils/settings';

import { safe } from 'lib/reducer';

let reduxKey = "customerDetail";

//build API
let api = reduxCrud(reduxKey, { 
	prepareFunction: () => ({}),
	fetchRequest: fetchRequest(({ unitId, id }) => `/api/${unitId}/customers/${id}`),
	createRequest: createRequest(({ unitId }) => `/api/${unitId}/customers`),
	updateRequest: updateRequest(({ unitId, id }) => `/api/${unitId}/customers/${id}`),
	deleteRequest: deleteRequest(({ unitId, id }) => `/api/${unitId}/customers/${id}`)
}); 

//export actions
export const fetchEntity = api.actions.fetchEntity;

export const prepareEntity = api.actions.prepareEntity;

export const saveEntity = api.actions.saveEntity;

export const deleteEntity = api.actions.deleteEntity;

export const selector = settingsSelector((state) => {
    if (!state || !state.get) {
        return {};
    }

    let periodParams = safe(state.getIn(["params", "period"]));
    let data = safe(state.get(reduxKey));

    return { ...data, periodParams };
});



export const fetchCustomerStats = (unitId, params) => ({
	type: reduxKey + "/FETCH_OVERVIEW",
	payload: backendRequest(`/api/${unitId}/customers/${params.cid}/overview`, "GET", { params }),
	meta: {
		unitId,
		params
	}
});

//clear stats!!!
api.reducer.handleAction(reduxKey + "/PREPARE_PENDING", (state, action) => state.setIn("overview", {}));

api.reducer.handleAction(reduxKey + "/FETCH_OVERVIEW_PENDING", (state, action) => state.set("overviewStatus", "pending"));
api.reducer.handleAction(reduxKey + "/FETCH_OVERVIEW_FULFILLED", (state, action) => state.set("overview", action.payload.body).set("overviewStatus", "success"));
api.reducer.handleAction(reduxKey + "/FETCH_STATS_REJECTED", (state, action) => state.set("overviewStatus", "failed").delete("overview"));


//export reducer
export default api.reducer.export();
