--Handle door opening effects

function GetLength(t)
	local l = 0
	for i,v in pairs(t) do
		l=l+1
	end
	return l
end

script.GetInStart.OnServerEvent:Connect(function(Player,Seat)
	if Seat:FindFirstChild("DoorHinge") then --This bit only serves a purpose if there are doors to open/close
		print("Found door hinge, opening door")
		if Seat.DoorHinge.ClassName ~= "HingeConstraint" then warn("Warning, door hinge is not actually a hinge!") end
		if SeatsInteractingPlayers[Seat] == nil then
			SeatsInteractingPlayers[Seat] = {} --This index is removed when the seat is destroyed by the seat add code
		end
		--Record that a player is trying to get in the seat
		SeatsInteractingPlayers[Seat][Player] = elapsedTime()
		--Activate the hinge
		Seat.DoorHinge.TargetAngle = 55
		--If the player doesnt stop trying to get in after 3 seconds, they probably left or it broke.
		wait(3)
		print("Check for automatic close")
		if Player.Parent ~= nil then --Player is still here, check they havent interacted again. 
			print("Player still here")
			if SeatsInteractingPlayers[Seat][Player] then
				print("Time since last interaction: "..tostring(elapsedTime() -  SeatsInteractingPlayers[Seat][Player]))
				if (elapsedTime() - SeatsInteractingPlayers[Seat][Player]) >=3 then --Check they havent started interacting again within 8 seconds
					SeatsInteractingPlayers[Seat][Player] = nil
					print("removing player")
				end
			end
		else
			SeatsInteractingPlayers[Seat][Player] = nil
		end
		print("Number of interacting players: "..tostring(GetLength(SeatsInteractingPlayers[Seat])))
		--Check if the door should be closed
		if GetLength(SeatsInteractingPlayers[Seat]) == 0 then
			Seat.DoorHinge.TargetAngle = 0
		end
	end
end)

script.GetInEnd.OnServerEvent:Connect(function(Player,Seat)
	if Seat:FindFirstChild("DoorHinge") then 
		if SeatsInteractingPlayers[Seat] then
			SeatsInteractingPlayers[Seat][Player] = nil
			--Check nobody is still trying to get in before closing
			if GetLength(SeatsInteractingPlayers[Seat]) == 0 then
				Seat.DoorHinge.TargetAngle = 0
			end
		end
	end
end)


return module
