import reduxCrud from 'lib/redux-crud';

import { fetchRequest, createRequest, updateRequest, deleteRequest } from 'lib/crud-backend';
import { listRequest, listResponse } from 'lib/list-backend';
import { settingsSelector } from 'utils/settings';

import { fromJS } from 'immutable';
import { safe } from 'lib/reducer';
import backendRequest from 'lib/backend';


export const reduxKey = "paymentCategoryDetail";

//build API
let api = reduxCrud(reduxKey, { 
	prepareFunction: (unit, type) => {
		return {
			currency: unit.currency,
			currencySymbol: unit.currencySymbol
		}
	},

	updateFetchPendingState: (state) => {
		return state.deleteIn(["payments"]);
	},
	fetchRequest: fetchRequest(({ unitId, id }) => `/api/${unitId}/payments/categories/${id}`),

	createRequest: createRequest(({ unitId }) => `/api/${unitId}/payments/categories`),
	updateRequest: updateRequest(({ unitId, id }) => `/api/${unitId}/payments/categories/${id}`),
	deleteRequest: deleteRequest(({ unitId, id }) => `/api/${unitId}/payments/categories/${id}`)
}); 


export function fetchPayments(unitId, id, period, paging, sorting) {
    //filter, paging, sorting, {...opts}
    let filter = { paymentId: id, ...period };
    if (!paging) {
        paging = { pageSize: 6 };
    }
    return {
        type: reduxKey + "/PAYMENTS_LIST",
        payload: listRequest(() => `/api/${unitId}/payments`)({ filter, paging, sorting }),
        meta: {
            filter,
            paging,
            sorting
        }
    }
}

api.reducer.handleAction(reduxKey + '/PAYMENTS_LIST_PENDING', (state, action) => 
    state
        .setIn(["payments", "status"], "pending")
);

api.reducer.handleAction(reduxKey + '/PAYMENTS_LIST_FULFILLED', (state, action) => 
    state
        .setIn(["payments"], fromJS(listResponse()(action.payload, action.meta)))
        .setIn(["payments", "status"], "success")
);

api.reducer.handleAction(reduxKey + '/PAYMENTS_LIST_REJECTED', (state, action) => 
    state
        .deleteIn(["payments"])
        .setIn(["payments", "error"], {}) //TODO
        .setIn(["payments", "status"], "failure")
);


export function paymentStatusReportAction(unitId, paymentId, period) {
    let params = { paymentId, ...period };
    return {
        type: '@@paymentCategoryDetail/STATUS_REPORT',
        payload: backendRequest(`/api/${unitId}/payments/reports/status`, "GET", { params }),
        meta: {
            unitId: unitId,
            params
        }
    }
}


// report
api.reducer.handleAction("@@paymentCategoryDetail/STATUS_REPORT_PENDING", (state, action) => state.setIn(["statusReport", "status"], "pending").setIn(["statusReport", "params"], action.meta.params));
api.reducer.handleAction("@@paymentCategoryDetail/STATUS_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));
});
api.reducer.handleAction("@@paymentCategoryDetail/STATUS_REPORT_REJECTED", (state, action) => state.setIn(["statusReport", "status"], "failure").deleteIn(["statusReport", "data"]) );


export function paymentTimelineReportAction(unitId, paymentId, period) {
    let params = { paymentId, ...period };
    return {
        type: '@@paymentCategoryDetail/TIMELINE_REPORT',
        payload: backendRequest(`/api/${unitId}/payments/reports/timeline`, "GET", { params }),
        meta: {
            unitId: unitId,
            params
        }
    }
}


// report
api.reducer.handleAction("@@paymentCategoryDetail/TIMELINE_REPORT_PENDING", (state, action) => state.setIn(["timelineReport", "status"], "pending").setIn(["timelineReport", "params"], action.meta.params));
api.reducer.handleAction("@@paymentCategoryDetail/TIMELINE_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));
});
api.reducer.handleAction("@@paymentCategoryDetail/TIMELINE_REPORT_REJECTED", (state, action) => state.setIn(["timelineReport", "status"], "failure").deleteIn(["timelineReport", "data"]) );





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

export const prepareEntity = api.actions.prepareEntity;

export const saveEntity = api.actions.saveEntity;

export const deleteEntity = api.actions.deleteEntity;

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



export const selector = settingsSelector((state) => {
    if (!state || !state.get) {
        return {};
    }

    let payments = safe(state.get(reduxKey));
    let periodParams = safe(state.getIn(["params", "period"]));
    return { ...payments, periodParams};
});




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