--[[
	Constructs special keys for property tables which connect property change
	listeners to an instance.
]]


local parseError = require(script.Parent.Parent.Dependencies).utility.parseError

local function OnChange(propertyName: string)
	local changeKey = {}
	changeKey.type = "SpecialKey"
	changeKey.kind = "OnChange"
	changeKey.stage = "observer"

	function changeKey:apply(callback: (property: unknown) -> (), applyTo: Instance, cleanupTasks: {})
		local ok, event = pcall(applyTo.GetPropertyChangedSignal, applyTo, propertyName)
		
		if not ok then
			parseError("cannotConnectChange", applyTo.ClassName, propertyName)
		elseif typeof(callback) ~= "function" then
			parseError("invalidChangeHandler", propertyName)
		else
			table.insert(cleanupTasks, event:Connect(function()
				callback((applyTo :: any)[propertyName])
			end))
		end
	end

	return changeKey
end

return OnChange
