--[[
	Bind events and animations to the character and humanoid
]]

local function BindToCharacter()
	local activeAnimation: AnimationTrack = nil
	local events = {}
	
	local character, humanoid = GetCharacter(LocalPlayer, true)
	local animator = humanoid:WaitForChild("Animator")::Animator
	local animateScript = character:WaitForChild("Animate")::LocalScript
	
	local defaultIdle = animateScript:WaitForChild("idle")
	local defaultIdleAnims = {}
	
	for _, defaultIdleAnimation in ipairs(defaultIdle:GetChildren()) do
		table.insert(defaultIdleAnims, defaultIdleAnimation:Clone())
	end
	
	--[[
		Play "special" animations when player plays a chord;
		controlled by the ChordPlayed BindableEvent
	]]
	table.insert(events, Replicated.Client.ChordPlayed.Event:Connect(function(chord: number, hold: boolean)
		local animation = GetAnimationFromChord(chord, hold)
		
		if activeAnimation then
			activeAnimation:Destroy()
		end
		
		activeAnimation = animator:LoadAnimation(animation)::AnimationTrack
		activeAnimation.Looped = false
		activeAnimation:Play()
	end))
	
	--[[
		Switch out idle animation for generic dance animation while player
		is on the dance floor; replace default idle animations when the
		player leaves a dance floor
		
		-- TODO: Revert to default idle animations when the music is stopped
	]]
	local wasOnDanceFloor = false
	table.insert(events, humanoid.Running:Connect(function(speed: number)
		local isOnDanceFloor = DanceFloorTracker.IsOnDanceFloor()
		
		if wasOnDanceFloor == isOnDanceFloor then
			return
		end
		
		wasOnDanceFloor = isOnDanceFloor
		defaultIdle:ClearAllChildren()
		
		if isOnDanceFloor then
			AnimationsDB.Generic:Clone().Parent = defaultIdle
		else
			for _, animation in ipairs(defaultIdleAnims) do
				animation:Clone().Parent = defaultIdle
			end
		end
	end))
	
	--[[
		If the player dies, disconnect all events and destroy the active animation,
		and re-bind events to the new humanoid/character instances
	]]
	table.insert(events, humanoid.Died:Connect(function()
		for _, event in ipairs(events) do
			event:Disconnect()
		end
		
		if activeAnimation then
			activeAnimation:Destroy()
		end
		
		BindToCharacter()
	end))
end

BindToCharacter()
