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

import { fromJS } from "immutable";


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

let reducer = createReducer(initialState);

export function cashflowReportAction(unitId, params = {}) {
	params.details = true;
	return {
		type: '@@cashflowReport/FETCH',
		payload: backendRequest(`/api/${unitId}/reports/cashflow`, "GET", { params }),
		meta: {
			unitId: unitId,
			params
		}
	}
}


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


export const selector = settingsSelector((state) => {
    let params = safe(state.getIn(["params", "period"]));
    let s = state.get("cashflowReport").toJS();
	return { ...s, params };
});

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