--[[
	Controls transparency of multiple Humanoids.
]]


local HumanoidController = require(script.Parent.HumanoidController)

local HumanoidControllers = {}
HumanoidControllers.__index = HumanoidControllers

function HumanoidControllers.new(playerList: { Player }, whitelist: { Player }?)
	local self = {
		playerList = playerList,
		whitelist = whitelist,
	}

	self.isHiding = false

	self.humanoidControllers = {}
	for _, player in ipairs(self.playerList) do
		self.humanoidControllers[player.UserId] = HumanoidController.new(player)
	end

	self.whitelistedUserIds = {}
	if self.whitelist then
		for _, player in ipairs(self.whitelist) do
			self.whitelistedUserIds[player.UserId] = true
		end
	end

	setmetatable(self, HumanoidControllers)

	return self
end

function HumanoidControllers:showHumanoids()
	self.isHiding = false
	for userId, humanoidController in pairs(self.humanoidControllers) do
		if not self.whitelistedUserIds[userId] then
			humanoidController:show()
		end
	end
end

function HumanoidControllers:hideHumanoids()
	self.isHiding = true
	for userId, humanoidController in pairs(self.humanoidControllers) do
		if not self.whitelistedUserIds[userId] then
			humanoidController:hide()
		end
	end
end

function HumanoidControllers:addHumanoidController(player: Player)
	if not self.humanoidControllers[player.UserId] then
		self.humanoidControllers[player.UserId] = HumanoidController.new(player)

		if self.isHiding then
			self.humanoidControllers[player.UserId]:hide()
		end
	else
		warn("Error: " .. player.Name .. " already has a HumanoidController.")
	end
end

function HumanoidControllers:removeHumanoidController(player: Player)
	if self.humanoidControllers[player.UserId] then
		self.humanoidControllers[player.UserId] = nil
	else
		warn("Error: " .. player.Name .. " does not have a HumanoidController to remove.")
	end
end

function HumanoidControllers:addToWhitelist(player: Player)
	if not self.whitelistedUserIds[player.UserId] then
		self.whitelistedUserIds[player.UserId] = player
	else
		warn("Error: " .. player.Name .. " is already part of the whitelist for HumanoidControllers.")
	end
end

function HumanoidControllers:removeFromWhitelist(player: Player)
	if self.whitelistedUserIds[player.UserId] ~= nil then
		self.whitelistedUserIds[player.UserId] = nil
	else
		warn("Error: " .. player.Name .. " is not part of the whitelist for HumanoidControllers.")
	end
end

function HumanoidControllers:waitForHumanoidAnimations()
	for _, humanoidController in pairs(self.humanoidControllers) do
		if humanoidController:isAnimating() then
			humanoidController.animationCompleted.Event:Wait()
		end
	end
end

return HumanoidControllers
