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

local alertPlayer = false
local CurrentTargets = {}
local PeopleAmount = {};

function Create()
	Ready = Time()
	Delay = 1
	this.Hostile = false
	this.Caged = false
	this.SubType = 0;
	this.following = false
end

local ContainmentUnits = {
	"RiotGuard"
}

local PeopleTarget = {
    "Prisoner", "Guard", "ArmedGuard", "Workman", "Janitor", "Sniper", "Teacher", "SpiritualLeader",
    "ParoleLawyer", "AppealsLawyer", "AppealsMagistrate", "Dog", "Soldier", "Doctor", "Paramedic", "Cook", "Gardener",
    "Warden", "Scientist", "Foreman", "Chief", "Psychologist", "Accountant", "Lawyer", "SiteDirector", "Technician",    "EliteOps", "SiteScientistDirector", "OfficeWorker"
} -- All entities in the game targetable by 096

local Fleeables = {
    "Prisoner", "Guard", "ArmedGuard", "Workman", "Janitor", "Sniper", "Teacher", "SpiritualLeader",
    "ParoleLawyer", "AppealsLawyer", "AppealsMagistrate", "Dog", "Soldier", "Doctor", "Paramedic", "Cook", "Gardener",
    "Warden", "Scientist", "Foreman", "Chief", "Psychologist", "Accountant", "Lawyer", "SiteDirector", "Technician",    "EliteOps", "SiteScientistDirector", "OfficeWorker"
} -- All entities in the game targetable by 106


local DoorsTarget = {
	 "Door", "JailDoorLarge", "StaffDoor", "SolitaryDoor"
}

function PanicPeople()
	local evac = this.GetNearbyObjects("EvacPoint", 9999)
	for obj, dist in pairs(evac) do
	for a,b in pairs(Fleeables) do
        targets = this.GetNearbyObjects(b, 8);
		if next(targets) ~= nil then
			for k,v in pairs(targets) do	
				Object.NavigateTo(k, obj.Pos.x, obj.Pos.y )
				end
			end
		end
	end
end

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


function clearTable(tbl)
    for i = 1, tableSize(tbl) do tbl[i] = nil; end
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

--BEGIN CODE--

function FindPeople()
		clearTable(PeopleAmount);
		for a,b in pairs(PeopleTarget) do
       		targets = this.GetNearbyObjects(b, 3);
			if next(targets) ~= nil then
				for k,v in pairs(targets) do
					if (k.Damage == 0) then
					this.Hostile = true
					this.Scare = true
					Hunt()
					end
					if tableSize(PeopleAmount) == 0 then
							this.Hostile = false
					end
				end	
			end
		end
end

function Hunt(elapsedTime)
	clearTable(CurrentTargets)
	    for a,b in pairs(PeopleTarget) do
        targets = this.GetNearbyObjects(b, 6);
		if next(targets) ~= nil then
			for k,v in pairs(targets) do
			if k.Damage < 1 then
				if tableSize(CurrentTargets) == 0 then
					this.Hostile = false
					end
				if roll(30) == true then
				table.insert(CurrentTargets, k)
				this.SubType = 1;
					AttackDoor()
					Attack()

					end
				end
			end
		end
	end
    Game.DebugOut("There are " .. tableSize(CurrentTargets) .. " Active Targets in 457's range.");
end


function Calculations() --Checks based on how many people are watching it, and will act based on the amount
		for a,b in pairs(PeopleTarget) do
       		targets = this.GetNearbyObjects(b, 6);
			if next(targets) ~= nil then
				for k,v in pairs(targets) do
					if tableSize(PeopleAmount) == 1 then
							Attack()
							AttackDoor()
						if getPercentageChance(25) then
						if alertPlayer == false then
							this.Sound( "__RiotHostages", "HostagesMusic1" )
							alertPlayer = true;
						end
							if (k.Damage == 0) then
							this.SubType = 1;
							Object.NavigateTo(k.Pos.x, k.Pos.y)
					elseif tableSize(PeopleAmount) >= 5 then
							Attack()
							AttackDoor()
						if getPercentageChance(50) then
							if (k.Damage == 0) then
							this.SubType = 1;
							Object.NavigateTo(k.Pos.x, k.Pos.y)
								end
							end
						end
					end
				end
			end
		end
	end
end

function Attack()
	for a,b in pairs(PeopleTarget) do
        targets = this.GetNearbyObjects(b, 1.6);
		if next(targets) ~= nil then
			for k,v in pairs(targets) do
				if (this.SubType == 1) then
				k.Damage = 1
				end
			end
		end
	end
end

function AttackDoor()
	for a,b in pairs(DoorsTarget) do
        targets = this.GetNearbyObjects(b, 1.6);
		if next(targets) ~= nil then
			for k,v in pairs(targets) do
				k.Damage = 1
			end
		end
	end
end

--RECONTAINING PROCEDURES--

function CagedMode()
	GetCaged()
	FollowMTF()
	UnFollowMTF()
end

function GetCaged()
	 for a,b in pairs(ContainmentUnits) do
        targets = this.GetNearbyObjects(b, 1);
		if next(targets) ~= nil then
			for k,v in pairs(targets) do
				if (k.SubType == 1) then
				this.SubType = 2;
				this.Caged = true
				this.Scare = false
				Interface.AddComponent(this,"UnFollow", "Button", "Unfollow MTF?")
				Interface.AddComponent(this,"Follow", "Button", "Follow MTF?")
				end
			end
		end
	end
end

function FollowMTF()
	if (this.following == true) then
		Game.DebugOut("I am follow")
		for a,b in pairs(ContainmentUnits) do
        targets = this.GetNearbyObjects(b, 8);
		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)
				end
				end
			end
		end
	end
end	

function FollowClicked()
	this.following = true
	this.RemoveInterfaceComponent("UncageThePeanut", "Uncage SCP 096?")
end

function UnFollowMTF()
	if (this.Caged == true) then
	if (this.following == false) then
		Object.ClearRouting()
		Game.DebugOut("I not follow")
		end
	end
end	

function UnFollowClicked()
	Interface.AddComponent(this, "UncageThePeanut", "Button", "Uncage SCP 096?")
	this.following = false
end

function UncageThePeanutClicked()
	this.Caged = false
	this.following = false
	this.SubType = 0;
	this.RemoveInterfaceComponent("UncageThePeanut", "Uncage SCP 966?")
	this.RemoveInterfaceComponent("Follow", "Follow MTF?")
	this.RemoveInterfaceComponent("UnFollow", "Unfollow MTF?")
end


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

function Update()
	if Time() > Ready then
		PerformUpdate( Delay )
		Ready = Ready + Delay
	end
end

function PerformUpdate( elapsedTime )
	if (this.Caged == false) then
	FindPeople()
	IdleMovement()
	if (this.Hostile == false) then
		this.SubType = 0;
		this.Scare = false
		end
	end
	target = CurrentTargets[1]
		if (target ~= nil) then
			Game.DebugOut("I am finding targets")
			Object.ClearRouting()
			Object.NavigateTo(this, target.Pos.x, target.Pos.y)
		end
	if (this.Scare == true) then
	PanicPeople()
	end
CagedMode()
end

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