--[[
	Connects the events for UI state.

	Returns a Rodux Signal class. This has the same API as RBXScriptSignal but
	lowercase. For example:

	```lua
	local store = Rodux.Store.new(reducer)
	local conn = uiStateEvents.connect(store)

	conn:disconnect()
	```
]]

function uiStatesEvents.connect(store)
	return store.changed:connect(function(newState: reducer.State, oldState: reducer.State)
		-- 3 booleans, one for each of the UI states
		local oldClosedState = not oldState.ui.merchBoothOpen
		local oldCatalogState = oldState.ui.merchBoothOpen and oldState.ui.viewedItemId == nil
		local oldItemState = oldState.ui.merchBoothOpen and oldState.ui.viewedItemId ~= nil

		local newClosedState = not newState.ui.merchBoothOpen
		local newCatalogState = newState.ui.merchBoothOpen and newState.ui.viewedItemId == nil
		local newItemState = newState.ui.merchBoothOpen and newState.ui.viewedItemId ~= nil

		if not oldClosedState and newClosedState then
			uiStatesEvents.merchBoothClosed:Fire()
		end
		if oldClosedState and not newClosedState then
			uiStatesEvents.merchBoothOpened:Fire()
		end

		if not oldCatalogState and newCatalogState then
			uiStatesEvents.catalogViewOpened:Fire()
		end
		if oldCatalogState and not newCatalogState then
			uiStatesEvents.catalogViewClosed:Fire()
		end

		if not oldItemState and newItemState then
			uiStatesEvents.itemViewOpened:Fire(newState.ui.viewedItemId)
		end
		if oldItemState and not newItemState then
			uiStatesEvents.itemViewClosed:Fire(oldState.ui.viewedItemId)
		end
	end)
end

return uiStatesEvents
