import createReducer 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",
    params: {
        from, to
    },
    data: {}
};

let reducer = createReducer(initialState);

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


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


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

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