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

import { unitI18n } from "utils/settings";

export const reduxKey = "settings";

//build API
let api = reduxCrud(reduxKey, { 
	fetchRequest: fetchRequest(({ unitId, id }) => `/api/${unitId}/unit/${id}`),
	updateRequest: updateRequest(({ unitId, id }) => `/api/${unitId}/unit/${id}`),

	onSaveSuccess: (state, action) => {
		let unit = action.payload.body;
		//TODO
		let i18n = unitI18n(unit);
		global.i18n = i18n;

		return state;
	}
}); 


api.reducer.handleAction("settingsLocale/SAVE_FULFILLED", (state, action) => state.mergeIn(["data"], action.meta.data));
api.reducer.handleAction("settingsTax/SAVE_FULFILLED", (state, action) => state.mergeIn(["data"], action.meta.data));
api.reducer.handleAction("settingsCompany/SAVE_FULFILLED", (state, action) => state.mergeIn(["data"], action.meta.data));
api.reducer.handleAction("settingsCustomization/SAVE_FULFILLED", (state, action) => state.mergeIn(["data"], action.meta.data));


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

export const saveEntity = api.actions.saveEntity;

export const selector = api.selector;

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