--[[
	

--]]




local DoorHandler = {}

local TweenService = game:GetService("TweenService")
local Player = game.Players.LocalPlayer

local Doors = {}
local DoorDis = 15

function DoorHandler:OpenDoor(v)
	local d = game.ReplicatedStorage.AnimatedDoor:Clone()
	d.Parent = workspace
	d:SetPrimaryPartCFrame(v.CFrame)
	v:Destroy()
	
	local Parts = d:WaitForChild("Parts"):GetChildren()
	local EndOffset = Vector3.new(0,d.Root.Size.Y/2,0)
	
	d.Root.Sound:Play()
	
	for i,v in pairs(Parts) do
		local info = TweenInfo.new(math.random(25,45)/10,Enum.EasingStyle.Sine,Enum.EasingDirection.Out)
		local props = {Size = Vector3.new(v.Size.X,0,v.Size.Z),CFrame = v.CFrame + EndOffset}
		TweenService:Create(v,info,props):Play()
		if math.random() > 0.5 then
			wait()
		end
	end
	
	wait(5)
	d:Destroy()
end

function DoorHandler:CloseDoor(v)
	local d = game.ReplicatedStorage.AnimatedDoor:Clone()
	d.Parent = workspace
	d:SetPrimaryPartCFrame(v.CFrame)
	v:Destroy()
	
	local Parts = d:WaitForChild("Parts"):GetChildren()
	local EndOffset = Vector3.new(0,d.Root.Size.Y/2,0)
	
	d.Root.Sound:Play()
	
	for i,v in pairs(Parts) do
		v.Size = Vector3.new(v.Size.X,0,v.Size.Z)
		v.CFrame = v.CFrame + EndOffset
		
		local info = TweenInfo.new(math.random(25,45)/10,Enum.EasingStyle.Sine,Enum.EasingDirection.Out)
		local props = {Size = Vector3.new(v.Size.X,d.Root.Size.Y,v.Size.Z),CFrame = v.CFrame - EndOffset}
		TweenService:Create(v,info,props):Play()
		if math.random() > 0.5 then
			wait()
		end
	end
	
	wait(5)
	d.Parts:Destroy()
	d.Root.Transparency = 0
	d.Root.CanCollide = true
end

function DoorHandler:Start()
	local Char = Player.Character or Player.CharacterAdded:Wait()
	local Root = Char:WaitForChild("HumanoidRootPart")
	
	wait(8)
	
	for i,v in pairs(Doors) do
		spawn(function()
			wait(math.random(1,5) + math.random())
			while true do
				local dis = (Root.Position - v.Position).Magnitude
				if dis <= DoorDis then
					break
				end
				wait(0.5)
			end
			DoorHandler:OpenDoor(v)
			return
		end)
	end
end


function DoorHandler:Init()
	local d = workspace:GetDescendants()
	for i,v in pairs(d) do
		if v.Name == "Door" then
			table.insert(Doors,v)
		end
		if math.random() > 0.95 then
			wait()
		end
	end
end


return DoorHandler
