--To Do:
-- Sanity Checks

local CurrentSeats = {}
local SeatsInteractingPlayers = {} --Each seat has a table of players containing the last interacting time from each playere

module = {}

function module.AddSeat(Seat)
	print("Adding seat")
	local EnterEvent = Instance.new("BindableEvent")
	local ExitEvent = Instance.new("BindableEvent")
	table.insert(CurrentSeats,Seat)
	script.NewSeat:FireAllClients(Seat)
	
	--Connect seat in listener
	local C1 = Seat.ChildAdded:Connect(function(Obj)
		if Obj.Name == "SeatWeld" then
			if Obj.Part1 then
				if Obj.Part1.Name == "HumanoidRootPart" then
					local Player = game.Players:GetPlayerFromCharacter(Obj.Part1.Parent)
					if Player then
						print("Enter event fired")
						EnterEvent:Fire(Player)
					end
				end
			end
		end
	end)
	
	local C2 = Seat.ChildRemoved:Connect(function(Obj)
		if Obj.Name == "SeatWeld" then
			if Obj.Part1 then
				if Obj.Part1.Name == "HumanoidRootPart" then
					local Player = game.Players:GetPlayerFromCharacter(Obj.Part1.Parent)
					if Player then
						print("Enter event fired")
						ExitEvent:Fire(Player)
					end
				end
			end
		end
	end)
	
	--Clean up after the seat is destroyed
	Seat.AncestryChanged:connect(function()
		if not Seat:IsDescendantOf(game) then
			C1:Disconnect()
			C2:Disconnect()
			EnterEvent:Destroy()
			ExitEvent:Destroy()
			SeatsInteractingPlayers[Seat] = nil 
			for i,v in pairs(CurrentSeats) do
				if v == Seat then
					v = nil
				end
			end
		end
	end)
	
	return EnterEvent,ExitEvent
end

function module.SeatCharacter(HRP,Seat)
	local sw = Instance.new("Weld")
	sw.Part0, sw.Part1 = Seat, HRP
	sw.C0, sw.C1 = CFrame.new(0, 0.5, 0, 1, 0, -0, 0, 0, 1, 0, -1, -0), CFrame.new(0, Seat.Size.Y*-.5+HRP.Size.Y*-.5, 0, 1, 0, -0, 0, 0, 1, 0, -1, -0)
	sw.Name = "SeatWeld"
	sw.Parent = Seat
end

script.GetSeats.OnServerInvoke = function(Player)
	return CurrentSeats	
end

script.GetInSeat.OnServerEvent:Connect(function(Player,Seat)
	if not Seat:FindFirstChild("SeatWeld") then
		if Player.Character ~= nil then
			local HRP = Player.Character:FindFirstChild("HumanoidRootPart")
			if HRP then
				local Dist = (HRP.Position - Seat.Position).magnitude
				if Dist<=10 then
					module.SeatCharacter(HRP,Seat)
				end
			end
		end
	end
end)
