--[=[
	Mounts the instance to the props. This handles mounting children, and events.

	The contract is that the props table is turned into observables. Note the following.

	* Keys of strings are turned into properties
		* If this can be turned into an observable, it will be used to subscribe to this event
		* Otherwise, we assign directly
	* Keys of functions are invoked on the instance in question
		* `(instance, value) -> Observable
		* If this returns an observable (or can be turned into one), we subscribe the event immediately
	* If the key is [Blend.Children] then we invoke mountChildren on it

	@param instance Instance
	@param props table
	@return Maid
]=]

function Blend.mount(instance, props)
	local maid = Maid.new()

	local parent = nil
	local dependentObservables = {}

	for key, value in pairs(props) do
		if type(key) == "string" then
			if key == "Parent" then
				parent = value
			else
				local observable = Blend.toPropertyObservable(value)
				if observable then
					maid:GiveTask(observable:Subscribe(function(result)
						task.spawn(function()
							instance[key] = result
						end)
					end))
				else
					task.spawn(function()
						instance[key] = value
					end)
				end
			end
		elseif type(key) == "function" then
			local observable = Blend.toEventObservable(key(instance, value))

			if Observable.isObservable(observable) then
				table.insert(dependentObservables, {observable, value})
			else
				warn(("Unable to apply event listener %q"):format(tostring(key)))
			end
		else
			warn(("Unable to apply property %q"):format(tostring(key)))
		end
	end

	-- Subscribe dependentObservables (which includes adding children)
	for _, event in pairs(dependentObservables) do
		maid:GiveTask(event[1]:Subscribe(Blend.toEventHandler(event[2])))
	end

	if parent then
		local observable = Blend.toPropertyObservable(parent)
		if observable then
			maid:GiveTask(observable:Subscribe(function(result)
				instance.Parent = result
			end))
		else
			instance.Parent = parent
		end
	end

	return maid
end


return Blend
