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

let reduxKey = "customerList";

//build API
let api = reduxList(reduxKey, { 
	fetchRequest: listRequest(({ unitId }) => `/api/${unitId}/customers`),
	fetchResponse: listResponse()
}); 

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

export function customerIncomeReportAction(unitId, params) {
    return {
        type: '@@customerIncomeReport/REPORT',
        payload: backendRequest(`/api/${unitId}/customers/income`, "GET", { params }),
        meta: {
            unitId: unitId,
            params
        }
    }
}

export function customerTimelineReportAction(unitId, params) {
    return {
        type: '@@customerTimelineReport/REPORT',
        payload: backendRequest(`/api/${unitId}/customers/timeline`, "GET", { params }),
        meta: {
            unitId: unitId,
            params
        }
    }
}

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

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



let safe = (val) => {
    return val ? val.toJS() : {};
}


export const selector = settingsSelector((state, props) => {
    let periodParams = safe(state.getIn(["params", "period"]));
    let customers = safe(state.get("customerList"));
    return { ...customers, periodParams };
});


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