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 expenseReportAction(unitId, params) {
    return {
        type: '@@expenseReport/FETCH',
        payload: backendRequest(`/api/${unitId}/reports/expense`, "GET", { params }),
        meta: {
            unitId: unitId,
            params
        }
    }
}


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


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

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