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

ENT.HealthPercentToGive = 20
ENT.AutomaticFrameAdvance = true 

function ENT:Initialize()
	self:SetMoveType( MOVETYPE_NONE )
	self:SetSolid( SOLID_NONE )
	self:SetModel( self.Model )
	
	self.initcur = CurTime() +0.1
	
	if !self.team then self.team = 0 end
end

function ENT:Think()
	local sequence = self:LookupSequence("idle")
	self:ResetSequence(sequence) 
	self:NextThink( CurTime() +0.01 )
	for k, v in pairs(ents.FindInSphere(self:GetPos(), 25)) do
		self:PlayerTouch(v)
	end
	return true
end

function ENT:CanPickup(ply)
	if self.team == 0 or self.team == ply:Team() then return true end
	return false
end

function ENT:PlayerTouch(ent)
	if ent:IsPlayer() and ValidEntity(ent) and ent:Health() > 0 and self:CanPickup(ent) and !self.pickedup and CurTime() > self.initcur then
		local health = ent:Health()
		local max_health = ent:GetNetworkedInt( "tf_ply_maxhealth" )
		if max_health == 0 then max_health = 100 end
		if health >= max_health then return end
		local healthtoadd = (max_health /100) *self.HealthPercentToGive
		local health_new
		if health +healthtoadd > max_health then
			health_new = max_health
		else
			health_new = health +healthtoadd
		end
		ent:SetHealth( health_new )
		self:EmitSound( "items/smallmedkit1.wav", 100, 100 )
		//self:EmitSound( "items/ammo_pickup.wav", 100, 100 ) (player emit)
		//self:EmitSound( "items\gunpickup2.wav", 100, 100 )
		self:Remove()
	end
end

function ENT:KeyValue( key, value )
	if !self.output then
		self.output = {}
	end
	
	if key == "TeamNum" then
		self.team = tonumber(value)
	end

	if key == "OnPlayerPickup" then
		if !self.output[key] then self.output[key] = {} end
		table.insert( self.output[key], value )
	end
end

function ENT:FireOutput( output_name )
	if !self.output[output_name] then return end
	for k, v in pairs( self.output[output_name] ) do
		local output_exp = string.Explode( ",", v )
		local output_ents = ents.FindByName( output_exp[1] )
		local output = output_exp[2]
		local output_params = output_exp[3]
		local output_delay = output_exp[4]
		local output_once = output_exp[5]
		for k, v in pairs( output_ents ) do
			v:Fire( output, output_params, tonumber(output_delay) )
			//Msg( "Fired output to " .. v:GetName() .. ": Output: " .. output .. "; params: " .. output_params .. "; delay: " .. output_delay .. "\n" )
		end
		if output_once == "-1" then
			self.newoutputs = {}
			for k, v in pairs( self.output ) do
				if v != output_exp[1] then
					self.newoutputs[k] = v
				end
			end
			self.output = self.newoutputs
			self.newoutputs = nil
		end
	end
end


function ENT:OnTakeDamage(dmg)
end

function ENT:OnRemove()
	if ValidEntity( self.parentent ) then
		self.parentent:Remove()
	end
end

