import reduxList from 'lib/redux-list';
import { listRequest, listResponse } from 'lib/list-backend';
import { settingsSelector } from 'utils/settings';
import backendRequest from 'lib/backend';
import createReducer, { safe } from 'lib/reducer';
import { fromJS } from 'immutable';

let initialState = {
    periodParams: {
        periodType: 'last12Months'
    },
    statusReport: {
        status: 'pending',
    },
    timelineReport: {
        status: 'pending',
    },
};

let reducer = createReducer(initialState);


export function paymentStatusReportAction(unitId, params) {
    return {
        type: '@@paymentStatusReport/REPORT',
        payload: backendRequest(`/api/${unitId}/payments/reports/status`, "GET", { params }),
        meta: {
            unitId: unitId,
            params
        }
    }
}


// report
reducer.handleAction("@@paymentStatusReport/REPORT_PENDING", (state, action) => state.setIn(["statusReport", "status"], "pending").setIn(["statusReport", "params"], action.meta.params));
reducer.handleAction("@@paymentStatusReport/REPORT_FULFILLED", (state, action) => {
    let { params, ...data } = action.payload.body;
    return state.setIn(["statusReport", "status"], "success").setIn(["statusReport", "params"], fromJS(params)).setIn(["statusReport", "data"], fromJS(data));
});
reducer.handleAction("@@paymentStatusReport/REPORT_REJECTED", (state, action) => state.setIn(["statusReport", "status"], "failure").deleteIn(["statusReport", "data"]) );


export function paymentTimelineReportAction(unitId, params) {
    return {
        type: '@@paymentTimelineReport/REPORT',
        payload: backendRequest(`/api/${unitId}/payments/reports/timeline`, "GET", { params }),
        meta: {
            unitId: unitId,
            params
        }
    }
}


// report
reducer.handleAction("@@paymentTimelineReport/REPORT_PENDING", (state, action) => state.setIn(["timelineReport", "status"], "pending").setIn(["timelineReport", "params"], action.meta.params));
reducer.handleAction("@@paymentTimelineReport/REPORT_FULFILLED", (state, action) => {
    let { params, ...data } = action.payload.body;
    return state.setIn(["timelineReport", "status"], "success").setIn(["timelineReport", "params"], fromJS(params)).setIn(["timelineReport", "data"], fromJS(data));
});
reducer.handleAction("@@paymentTimelineReport/REPORT_REJECTED", (state, action) => state.setIn(["timelineReport", "status"], "failure").deleteIn(["timelineReport", "data"]) );


//build API
let api = reduxList('paymentList', { 
    reducer,
	fetchRequest: listRequest(({ unitId }) => `/api/${unitId}/payments`),
	fetchResponse: listResponse()
}); 

//export actions
export const fetchList = api.actions.fetchList;

//unit selector
export const selector = settingsSelector(api.selector);


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