import reduxCrud from 'lib/redux-crud';

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

import moment from 'moment';
import { injectPeriodParams } from 'containers/Params';

export const reduxKey = "paymentDetail";

//build API
let api = reduxCrud(reduxKey, { 
	prepareFunction: async (unit, type, categoryId) => {
		let recurring = type == "rec";
		let p = {
			recurring,
			currency: unit.currency,
			currencySymbol: unit.currencySymbol,
			status: "ISSUED"
		}

		if (recurring) {
			p.frequency = 'M';
			p.dateFrom = moment().format("YYYY-MM-DD")
		} else {
			p.dueDate = moment().format("YYYY-MM-DD")
		}

		if (categoryId) {
			try {
				//TODO refactor?
				let request = await fetchRequest(({ unitId, id }) => `/api/${unitId}/payments/categories/${id}`);
				let category = await request({ unitId: unit.id, id: categoryId });
				p.payment = category.body;
			} catch (e) {
				console.error(e);
			}
		}

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


//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(injectPeriodParams(api.selector));

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