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

import { fromJS } from "immutable";

import moment from 'moment';

const m = moment().subtract(1, "year");
const from = m.startOf("year").format("YYYY-MM-DD"), to = m.endOf("year").format("YYYY-MM-DD");

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

let reducer = createReducer(initialState);

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


reducer.handleAction("@@paymentReport/FETCH_PENDING", (state, action) => state.set("status", "pending"));
reducer.handleAction("@@paymentReport/FETCH_FULFILLED", (state, action) => {
	let { params, ...data } = action.payload.body;
	return state.set("status", "success").set("data", fromJS(data));
});
reducer.handleAction("@@paymentReport/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("paymentReport").toJS();
	return { ...s, params };
});

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

