import createReducer from 'lib/reducer';
import backendRequest from 'lib/backend';
import { settingsSelector } from 'utils/settings';

import { fromJS } from "immutable";


const initialState = {
	status: "pending",
	params: {},
	data: {}
};

let reducer = createReducer(initialState);

export function customerReportAction(unitId, params) {
	return {
		type: '@@customerReport/FETCH',
		payload: backendRequest(`/api/${unitId}/reports/customer`, "GET", { params }),
		meta: {
			unitId: unitId,
			params
		}
	}
}


reducer.handleAction("@@customerReport/FETCH_PENDING", (state, action) => state.set("status", "pending").set("params", action.meta.params));
reducer.handleAction("@@customerReport/FETCH_FULFILLED", (state, action) => {
	let { params, ...data } = action.payload.body;
	return state.set("status", "success").set("params", fromJS(params)).set("data", fromJS(data));
});
reducer.handleAction("@@customerReport/FETCH_REJECTED", (state, action) => state.set("status", "failure").delete("data") );


export const selector = settingsSelector((state) => {
	return state.get("customerReport").toJS();
});

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