local ScenarioUtils = import('/lua/sim/ScenarioUtilities.lua')
#local mapPath = SHGetFolderPath('PERSONAL') .. '/My Games/Gas Powered Games/Supreme Commander Forged Alliance/maps'
local ScenarioFramework = import('/lua/ScenarioFramework.lua')

--units to be restricted
local NAVALbuildRestriction = categories.NAVAL + categories.ANTINAVY

local rectSizeX = 6
local rectSizeY = 9

function OnPopulate()
	ScenarioUtils.InitializeArmies()	
	local self = import('/lua/sim/Entity.lua').Entity()
	ForkThread(PrintCake, self)
	for k = 1, 8 do
		local entryName = 'Entry_' .. k
		local exitName = 'Exit_' .. k
		
		local entryPos = ScenarioUtils.MarkerToPosition(entryName)
		local exitPos = ScenarioUtils.MarkerToPosition(exitName)
		ForkThread(TeleportThread, self, entryPos, exitPos)
		CreateTeleportMaintenanceEffects(entryPos, exitPos)
	end
   local tblArmy = ListArmies()
   for index,army in tblArmy do
      ScenarioFramework.AddRestriction(army, NAVALbuildRestriction)
   end
end

PrintCake = function(self)
	ForkThread(RandomFun, self)
	local checkSum = 8
	local ranSumA = Random(1, 8)
	local ranSumB = Random(1, 8)
	local ranSumC = Random(1, 8)
	local ranSumD = Random(1, 8)
	if ranSumD == checkSum then
		WaitSeconds(4)
		PrintText("Due to scheduled maintenance the next test is currently unavailable. ", 18, 'fff57900', 3, 'center')
		WaitSeconds(2)
		PrintText("It has been replaced with a live fire course designed for military androids. ", 18, 'fff57900', 3, 'center')
		WaitSeconds(2)
		PrintText("The Enrichment Center apologizes and wishes you the best of luck.", 18, 'fff57900', 3, 'center')
	end
	if ranSumA == checkSum then
		WaitSeconds(8)
		PrintText('Go for the Cake!', 30, 'fff57900', 4, 'center')
	end
	if ranSumB == checkSum then
		WaitSeconds(1800)
		PrintText('The Cake is a LIE', 30, 'fff57900', 4, 'center')
	end
	if ranSumC == checkSum then
		WaitSeconds(1200)
		PrintText('Can you hear me?', 30, 'fff57900', 4, 'center')
	end
end

RandomFun = function(self)
	local messageT = {

		"Grief counseling and cake will be available at the end of the testing period.",
		"Please note that we have added a consequence for failure. Any contact with the chamber floor will result in an unsatisfactory mark on your official testing record, followed by death. ",
		"This is your fault. I amm going to kill you. And all the cake is gone. You do nott even care. ",
		"You are not a good person. You know that, right? Good people don't end up here. ",
		"Did you know you can donate one or all of your vital organs to the Aperture Science Self Esteem Fund for Girls? It's true! ",
		"Remember, the Aperture Science 'Bring Your Daughter to Work Day' is the perfect time to have her tested. ",
		"Momentum, a function of mass and velocity, is conserved between portals. In layman's terms, speedy thing goes in, speedy thing comes out. ",
		"Please be advised that a noticeable taste of blood is not part of any test protocol, but is an unintended side effect of the Aperture Science Material Emancipation Grid, which may, in semi-rare cases, emancipate dental fillings, crowns, tooth enamel and teeth. ",
		"Unbelievable. You, **subject name here** must be the pride of **subject hometown here**. ",
		"You think you're doing some damage? Two plus two is...[sparking and fizzling noise] Ten. IN BASE FOUR! I'M FINE! ",
		"Who are you? What is that? Oh! What's that? What's THAT? What is THAT? ",
		"Ooooh! That thing has numbers on it. ",
		"Hey! Look at that thing. No, that other thing! ",
		"Where are we going? Are you coming back? What's that noise? Is that a gun? Do you smell something burning? Ooooohh... what's in heeeere? ",
		"Oh hey! You're the lady from the test. Hi! ",
		"Area and state regulations do not allow the Companion Cube to remain here, alone and companionless. ",
		"As part of an optional test protocol, we are pleased to present an amusing fact: The Device is now more valuable than the organs and combined incomes of everyone in *subject hometown here*. ",
		"Have I lied to you?... I mean, in this room? ",
		"Maybe you should marry that thing since you love it so much. Do you want to marry it? WELL I WON'T LET YOU! How does that feel? ",
		"There was even going to be a party for you. A big party, that all your friends were invited to. I invited your best friend, the Companion Cube. Of course, he couldn't come because you murdered him. All your other friends couldn't come either, because you don't have any other friends, because of how unlikable you are. It says so right here in your personnel file: 'Unlikable. Liked by no one. A bitter, unlikable loner, whose passing shall not be mourned.' Shall NOT be mourned. That's exactly what it says. Very formal. Very official. It also says you were adopted, so that's funny, too. ",
		"While it has been a faithful companion, your Companion Cube cannot accompany you through the rest of the test. If it could talk - and the Enrichment Center takes this opportunity to remind you that it cannot - it would tell you to go on without it, because it would rather die in a fire than become a burden to you. ",
		"The Enrichment Center reminds you that the Weighted Companion Cube will never threaten to stab you and, in fact, cannot speak. ",
		"As part of a required Enrichment Center protocol, the previous statement that we would not monitor the test area was a complete fabrication. We will stop enhancing the truth in three... two... *zzzt* ",
		"Your entire life has been a mathematical error... a mathematical error I'm about to correct! ",
		"You are kidding me. Did you just stuff that Aperture Science Thing-we-don't-know-what-it-does into an Aperture Science Emergency Intelligence Incinerator? ",
		"When I said 'deadly neurotoxin,' the 'deadly' was in massive sarcasm quotes. I could take a bath in this stuff. Put in on cereal, rub it right into my eyes... honestly, it's not deadly at all... to *me*. You, on the other hand, are going to find its deadliness... a lot less funny. ",
		"Well, you found me. Congratulations. Was it worth it? Because, despite your violent behavior, the only thing you've managed to break so far... is my heart. Maybe you could settle for that, and we'll just call it a day. I guess we both know that isn't going to happen. ",
		"Time out for a second. That wasn't supposed to happen. Do you see that thing that fell out of me? What is that? It's not the surprise. I've never seen it before! Never mind. It's a mystery I'll solve later... by myself, because you'll be dead. ",
		"That thing is probably a waste container, go ahead and rub it all over your face. ",
		"This isn't brave. It's murder. ",
		"Good news. I figured what that thing you just incinerated did. It was a morality core they installed after I flooded the Enrichment Center with a deadly neurotoxin, to make me stop flooding the Enrichment Center with a deadly neurotoxin. So get comfortable while I warm up the neurotoxin emitters. ",
		"That thing you burned up isn't important to me, it's the fluid catalytic cracking unit. It makes shoes for orphans... nice job breaking it, hero. ",
		"At the end of the experiment, you will be baked ... and then there will be  ... cake.",
	}

	local counter = 1
	local tablesize = table.getn(messageT)
	local tabRan
	while true do
		tabRan = Random(1, tablesize)
		WaitSeconds(Random(300, 600))
		PrintText(messageT[tabRan], 12, 'fff57900', 15, 'center')
	end
end
	


TeleportThread = function(self, entryPos, exitPos)
	local ex, ey, ez = unpack(entryPos)
	local tx, ty, tz = unpack(exitPos)
	local entryRect = Rect(ex - rectSizeX/2, ez - rectSizeY/2, ex + rectSizeX/2, ez + rectSizeY/2)
	local exitRect = Rect(tx - rectSizeX/2, tz - rectSizeY/2, tx + rectSizeX/2, tz + rectSizeY/2)
	local counter -- wtf value just to havy ANY value at until
	local telUnits
	local killUnits
	while true do 
		telUnits = GetUnitsInRect( entryRect)
		killUnits = GetUnitsInRect( exitRect)
		if telUnits ~= nil then
			if table.getn(telUnits) >= 1 then
				for k, v in telUnits do
					if table.find(v:GetBlueprint().Categories,'AIR')  then	
					#v:GetPosition()
					else
						ForkThread(WarpThread,self, entryPos, exitPos, v)
					end
				end
			end
		end
		if killUnits ~= nil then
			if table.getn(killUnits) >= 1 then
				for k, v in killUnits do
					if table.find(v:GetBlueprint().Categories,'STRUCTURE') then
						v:Destroy()
					end
				end
			end
		end
		WaitSeconds(1)
	end
end

WarpThread = function(self, entryPos, exitPos, v)
	local ex, ey, ez = unpack(entryPos)
	local tx, ty, tz = unpack(exitPos)



	if table.find(v:GetBlueprint().Categories,'MOBILE') or table.find(v:GetBlueprint().Categories,'PROJECTILE') then

			Warp(v, Vector( tx + Random(-rectSizeX/0.2, rectSizeX/0.2)/10, ty, tz + Random(-rectSizeY/0.2, rectSizeY/0.2)/10))
			#print('uzoom')

	elseif table.find(v:GetBlueprint().Categories,'STRUCTURE') then
		v:Destroy()
	end
end

function CreateTeleportMaintenanceEffects (entryPos, exitPos)
	#local ex, ey, ez = unpack(entryPos)
	#local tx, ty, tz = unpack(exitPos)


	#CreateUnitHPR('uel0001', 1, ex - rectSizeX/2, ey,ez - rectSizeY/2 , -180, 0, 0) 
	#CreateUnitHPR('uel0001', 1, ex + rectSizeX/2, ey,ez - rectSizeY/2 , -180, 0, 0) 
	#CreateUnitHPR('uel0001', 1, ex - rectSizeX/2, ey,ez + rectSizeY/2 , -180, 0, 0) 
	#CreateUnitHPR('uel0001', 1, ex + rectSizeX/2, ey,ez + rectSizeY/2 , -180, 0, 0) 
	
	local entryEnt = import('/lua/sim/Entity.lua').Entity()
	local exitEnt = import('/lua/sim/Entity.lua').Entity()
	Warp(entryEnt, Vector(entryPos[1],entryPos[2] + 0.2,entryPos[3] ))
	Warp( exitEnt, Vector(exitPos[1],exitPos[2] + 0.2,exitPos[3] ))
	
	CreateEmitterAtEntity(entryEnt,1, '/effects/emitters/uef_orbital_death_laser_end_distort_emit.bp')
	CreateEmitterAtEntity(exitEnt,1,'/effects/emitters/uef_orbital_death_laser_end_distort_emit.bp')  
	
	CreateEmitterAtEntity(entryEnt,1, '/effects/emitters/phason_laser_end_01_emit.bp')
	CreateEmitterAtEntity(exitEnt,1, '/effects/emitters/phason_laser_end_01_emit.bp')  
	
--	CreateEmitterAtEntity(entryEnt,1, '/effects/emitters/aeon_shield_generator_mobile_01_emit.bp')
--	CreateEmitterAtEntity(exitEnt,1, '/effects/emitters/aeon_shield_generator_mobile_01_emit.bp')  



	
end
function OnStart(self)
   --delete all units on the water layers except air units every 2 seconds
   ForkThread(function()
      while true do
         WaitSeconds(2)
         killUnitsOnLayer({'Seabed','Sub'},{'AIR'})
      end
   end)
   
end








--get all units on the map
allUnits = function()
     local xmapsize = ScenarioInfo.size[1]
     local ymapsize = ScenarioInfo.size[2]
     local mapRect = {x0 = 0, x1 = xmapsize, y0 = 0, y1 = ymapsize}
     units = GetUnitsInRect(mapRect)
    return units
end

--delete all units on a layer exept those containing the exception categories
killUnitsOnLayer = function(layers,exceptions)
   --get all units on the map
   local units = allUnits()
   --if there are units on the map
   if units and table.getn(units) > 0 then
      for index,unit in units do
         local delete = false
         
         --is the unit on one of the specified layers?
         for index,layer in layers do
            if unit:GetCurrentLayer() == layer then
               delete = true
            end
         end
         
         --is the unit in an exception category?
         for index,category in exceptions do
            if EntityCategoryContains(categories[category], unit) then
               delete = false
            end
         end
         
         --if the unit is in one of the layers and in no exception category then kill it
         if  delete == true then
            if unit and not unit:IsDead() then
               unit:Kill()
            end
         end
      end
   end
end 

