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

import { fromJS } from "immutable";


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

let reducer = createReducer(initialState);

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


reducer.handleAction("@@summaryReport/FETCH_PENDING", (state, action) => state.set("status", "pending").set("params", action.meta.params));
reducer.handleAction("@@summaryReport/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("@@summaryReport/FETCH_REJECTED", (state, action) => state.set("status", "failure").delete("data") );


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

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