export function getInitialState() {
	const d = window.edfwData || {};
	return {
		settings: d.settings || {},
		rules: d.rules || {},
		meta: d.meta || {},
		capabilities: d.capabilities || {},
		schema: d.schema || [],
		dirty: false,
	};
}

export function reducer( state, action ) {
	switch ( action.type ) {
		case 'SET_FIELD':
			return {
				...state,
				dirty: true,
				settings: { ...state.settings, [ action.key ]: action.value },
			};
		case 'SET_RULE':
			return {
				...state,
				dirty: true,
				rules: { ...state.rules, [ action.key ]: { ...state.rules[ action.key ], ...action.patch } },
			};
		case 'ADD_RULE':
			return { ...state, dirty: true, rules: { ...state.rules, [ action.key ]: action.rule } };
		case 'SET_RULES':
			return { ...state, dirty: true, rules: action.rules };
		case 'REMOVE_RULE': {
			const next = { ...state.rules };
			delete next[ action.key ];
			return { ...state, dirty: true, rules: next };
		}
		case 'SET_HOLIDAYS':
			return {
				...state,
				dirty: true,
				settings: { ...state.settings, skipped_dates: action.holidays },
			};
		case 'HYDRATE':
			return {
				...state,
				settings: action.settings,
				rules: action.rules,
				schema: action.schema || state.schema,
				dirty: false,
			};
		case 'MARK_SAVED':
			return { ...state, dirty: false };
		default:
			return state;
	}
}
