--[[
	Controls transparency of Humanoid parts.
]]


local HumanoidController = {}
HumanoidController.__index = HumanoidController

local States = {
	Idle = 0,
	Animating = 1,
}

function HumanoidController.new(player)
	local self = {
		player = player,
		characterParts = {},
		state = States.Idle,
		animationCompleted = Instance.new("BindableEvent"),
		spring = Otter.spring,
	}

	self.setOriginalTransparencies = function()
		local character = self.player.Character
		if character and self.state == States.Idle then
			for _, descendant in ipairs(character:GetDescendants()) do
				if descendant:IsA("BasePart") or descendant:IsA("Decal") then
					self.characterParts[descendant] = descendant.Transparency
				end
			end
		end
	end

	self.motor = Otter.createSingleMotor(0)
	self.motor:onStep(function(value)
		for part, originalTransparency in pairs(self.characterParts) do
			part.Transparency = math.max(value, originalTransparency)
		end
	end)
	self.motor:onComplete(function(value: number)
		if value == 1 then
			local character = self.player.Character
			if not character then
				return
			end

			character.Parent = ReplicatedStorage -- Move the character out of the world
		end

		self.state = States.Idle
		self.animationCompleted:Fire()
	end)

	setmetatable(self, HumanoidController)

	return self
end

function HumanoidController:show()
	local character = self.player.Character
	if not character then
		return
	end

	character.Parent = workspace -- Place character back to the world

	self.state = States.Animating
	self.motor:setGoal(self.spring(0))
end

function HumanoidController:hide()
	self.setOriginalTransparencies()

	self.state = States.Animating
	self.motor:setGoal(self.spring(1))
end

function HumanoidController:isAnimating()
	return self.state == States.Animating
end

return HumanoidController
