// Available variables:
// - Machine
// - interpret
// - assign
// - send
// - sendParent
// - spawn
// - raise
// - actions
// - XState (all XState exports)

const initialState = {
	selectedFilters: [],
	searchedFilters: [],
	searchTerm: "",
	page: 1,
	retries: 0,
};

const fetchMachine = Machine({
	id: "peopleFilters",
	initial: "closed",
	context: Object.assign({}, initialState),
	states: {
		closed: {
			on: {
				OPEN: "open",
				SEARCH: 'loading'
			},
		},
		open: {
			on: {
				CLOSE: "closed",
				SELECT: {
					actions: assign({
						selectedFilters: context => [...selectedFilters, context.filter]
					})
				},
				UNSELECT: {
					actions: assign({
						selectedFilters: context => [...selectedFilters].filter(item => item !== context.filter)
					})
				},
				SEARCH: 'loading'
			},
		},
		loading: {
			on: {
				SUCCESS: {
					target: "closed"
				},
				FAILURE: {
					target: "failure"
				}
			}
		},
		failure: {
			on: {
				RETRY: {
					target: "loading",
					actions: assign({
						retries: (context, event) => context.retries + 1
					})
				}
			}
		}
	},
	on: {
		RESET: {
			target: 'closed',
			actions: assign(Object.assign({}, initialState))
		},
		VIEW_MORE: {
			target: 'loading',
			actions: assign({
				page: (context, event) => context.page + 1
			})
		}
	},
});