AddCSLuaFile( "cl_init.lua" )
AddCSLuaFile( "shared.lua" )
include( 'shared.lua' )

function ENT:SpawnFunction( userid, tr )

	local trace = util.GetPlayerTrace( userid, userid:GetAimVector() )
	local tr = util.TraceLine( trace )
	local thisent = ents.Create( "combine_lock" )
		thisent:SetPos( tr.HitPos + tr.HitNormal * 32 )
--		thisent:SetAngles( tr.HitNormal:Angle() )
		thisent:Spawn()
	thisent:Activate()

end

function ENT:Initialize()

self.BeepShit = {

	Sound( "buttons/combine_button1.wav" );
	Sound( "buttons/combine_button2.wav" );
	Sound( "buttons/combine_button3.wav" );
	Sound( "buttons/combine_button5.wav" );
	Sound( "buttons/combine_button7.wav" );

}

self.Entity:SetModel("models/props_combine/combine_lock01.mdl")
self.Entity:PhysicsInit( SOLID_VPHYSICS )
self.Entity:SetMoveType( MOVETYPE_VPHYSICS )
self.Entity:SetSolid( SOLID_VPHYSICS )
util.PrecacheSound("buttons/combine_button_locked.wav")
self.Locked = true
self.UnLocked = false
self.Timer = CurTime() + 2.5

end

function ENT:OnTakeDamage()

    local vPoint = self.Entity:GetPos()
    local effectdata = EffectData()
    effectdata:SetStart(vPoint)
    effectdata:SetOrigin(vPoint)
    effectdata:SetScale(1)
    util.Effect("Explosion", effectdata)
	self.Entity:Remove()
		
end

function ENT:PhysicsCollide(data, physobj)

	if string.find(data.HitEntity:GetClass(),"door") then
		constraint.Weld(self.Entity,data.HitEntity,0,0,0)
	end
	
end

function ENT:Use( activator, caller )

	 if self.Timer < CurTime() then
			self.Timer = CurTime() + 1
		
		if caller:IsCombineDefense() then
		
		self.Entity:EmitSound( self.BeepShit[math.random( 1, #self.BeepShit )] );

			if self.Locked == true then
				self.Locked = false
			
			elseif self.Locked == false then
				self.Locked = true
			
			end
			
		end
		
		if !caller:IsCombineDefense() then
			self.Entity:EmitSound("buttons/combine_button_locked.wav", 75, 100)
		end
		
	end
	
end

function ENT:StartTouch()

end

function ENT:EndTouch()

end

local function lock(xent)

	local doors=ents.FindInSphere(xent:GetPos(),10)
		for i=1,table.getn(doors) do
			if doors[i]:GetClass()=="prop_door_rotating" then
				doors[i]:Fire("lock","",0)
				doors[i]:Fire("close","",0)
				
			else
			doors[i]:Fire("lock","",0)
			doors[i]:Fire("close","",0)
			end
		end
		
end

local function unlock(xent)

	local doors=ents.FindInSphere(xent:GetPos(),10)
		for i=1,table.getn(doors) do
			if doors[i]:GetClass()=="prop_door_rotating" then
				doors[i]:Fire("unlock","",0)
				
			else
			doors[i]:Fire("unlock","",0)
			end
		end
		
end

function ENT:Think()
	
	if self.Locked == true then
	lock(self.Entity)
	end
	
	if self.Locked == false then
	unlock(self.Entity)
	end
	
end

