local Time 	= Game.Time;
local Delay 	= 3; -- game seconds
local Ready	= Time();

local Animation = { [1] = 0, [2] = 1, [3] = 2, [4] = 3 }
local Frame = 1;

local Destroyables = {
	"SCP_049", "SCP_049_1", "ChaosInsurgent", "SCP_008_1"
}

local Crashables = {
	"SCP_049"
}

function Create()
	Ready = Time()
	Delay = 3
end

function SpawnObject(ObjectType, x, y)
    return Object.Spawn(tostring(ObjectType), x, y);
end

function tableSize(T)
    if T == nil then return 0; end
    local count = 0;
    for _ in pairs(T) do count = count + 1; end
    return count;
end

function FindGuys()
for a,b in pairs(Destroyables) do
        targets = this.GetNearbyObjects(b, 9999);
		if next(targets) ~= nil then
			for k,v in pairs(targets) do
			if (k.Damage == 0) then
			Object.ClearRouting()
			Object.NavigateTo(k.Pos.x, k.Pos.y)
			KillEntity()
				end
			end
		end
	end
end

function KillEntity()
	for a,b in pairs(Destroyables) do
        targets = this.GetNearbyObjects(b, 15);
		if next(targets) ~= nil then
			for k,v in pairs(targets) do
			if (k.Damage == 0) then
			this.Sound("_Tools", "Attack_AssaultRifle")
			k.Damage = 1
				end
			end
		end
	end
end

function GetCrashed()
	for a,b in pairs(Crashables) do
        targets = this.GetNearbyObjects(b, 25);
		if next(targets) ~= nil then
			for k,v in pairs(targets) do
				if (this.Damage == 0) then
					Object.Sound("Mine","Explosion");
					this.Damge = 1	
					this.ApplyVelocity( math.random(-10,10),math.random(-10,10),math.random(-10,10))
					this.fade = 14;
					local n = SpawnObject("RiotGuard", this.Pos.x, this.Pos.y);
					Object.ApplyVelocity(n, math.random(-10,10),math.random(-10,10),math.random(-10,10))
					local f = SpawnObject("Fire", this.Pos.x, this.Pos.y);
					local f = SpawnObject("Fire", this.Pos.x, this.Pos.y);
					local g = SpawnObject("Fire", this.Pos.x, this.Pos.y);
					local g = SpawnObject("Fire", this.Pos.x, this.Pos.y);
					Object.ApplyVelocity(f, math.random(-10,10),math.random(-10,10),math.random(-10,10))
					Object.ApplyVelocity(g, math.random(-10,10),math.random(-10,10),math.random(-10,10))
					n.Damage = 1
					local C = SpawnObject("SCPAttackHeliCopterCrashed", this.Pos.x, this.Pos.y);
					C.Damage = 1
					this.Delete()
				end
			end
		end
	end
end

function IdleMovement() --the idle movement or just not when doing anything
	if roll(30) == true then
            this.NavigateTo(this.Pos.x + math.random(-20,20),this.Pos.y + math.random(-20,20))
		end
	end

function Update()
	this.SubType = Animation[Frame];
	Frame = Frame + 1;
	if Frame > #Animation then -- #Animation = length of Animation array = 4
		Frame = 1;
	end
	if Time() > Ready then
		PerformUpdate( Delay )
		Ready = Ready + Delay
	end
end

function PerformUpdate( elapsedTime )
	IdleMovement()
	FindGuys()
	GetCrashed()
	end

function roll(chance)
    local randomPercent = math.random(0, 50);
    if randomPercent <= chance then return true; end
    return false;
end
