--[[
    Connects the events for UI state.

    Connects the events for item addition/removal in the given store.

    The `selector` is a function that takes the store's state as an argument and
	returns the items table from it.

    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 = itemEvents.connect(store)

    conn:disconnect()
    ```
]]

function itemEvents.connect(store, selector: (table) -> itemInfo.State)
	return store.changed:connect(function(newState: table, oldState: table)
		local oldItemInfo = selector(oldState)
		local newItemInfo = selector(newState)
		if oldItemInfo == newItemInfo then
			return
		end

		for newId, newInfo in pairs(newItemInfo) do
			if not oldItemInfo[newId] then
				-- IDs are converted to number for consistency with the addItemAsync API
				itemEvents.itemAdded:Fire(tonumber(newId), newInfo)
			end
		end

		for oldId, _ in pairs(oldItemInfo) do
			if not newItemInfo[oldId] then
				itemEvents.itemRemoved:Fire(tonumber(oldId))
			end
		end
	end)
end

return itemEvents
