import { safe } from 'lib/reducer';
import reduxCrud from 'lib/redux-crud';
import moment from "moment";

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

export const reduxKey = "invoiceDetail";

let modifyResponse = (body) => {
	if (body.project) {
		body.include_project = true;
	}
	return body;
};

//build API
let api = reduxCrud(reduxKey, { 
	prepareFunction: (unit) => {
		let m = moment();
		let inv = {
			currency: unit.currency,
			currencySymbol: unit.currencySymbol,

			subjectName: unit.name,
			subjectIdNumber: unit.idNumber,
			subjectTaxNumber: unit.taxNumber,
			subjectAddress: unit.address,

			status: "DRAFT", //TODO
			createdDate: m.format("YYYY-MM-DD"),
			invoiceDate: m.format("YYYY-MM-DD"),

			totalAmount: 0,
			totalPayable: 0,

			template: unit.invoiceTemplate,
			templateLang: unit.invoiceTemplateLang,

			thankYouNote: unit.invoiceThankYouNote
		};

		let paymentMethods = unit.paymentMethods;

		//payment methods
		if (Array.isArray(paymentMethods)) {
			inv.paymentMethods = [];

			for (let i = 0; i < paymentMethods.length; i++) {
				let pm = paymentMethods[i];
				if (pm.defaultMethod) {
					inv.paymentMethods.push({
						...pm,
						defaultMethod: null
					});
				}
			}
		}

		return inv;
	},
	fetchRequest: fetchRequest(({ unitId, id }) => `/api/${unitId}/invoices/${id}`, modifyResponse),
	createRequest: createRequest(({ unitId }) => `/api/${unitId}/invoices`, modifyResponse),
	updateRequest: updateRequest(({ unitId, id }) => `/api/${unitId}/invoices/${id}`, modifyResponse),
	deleteRequest: deleteRequest(({ unitId, id }) => `/api/${unitId}/invoices/${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();
