-----------------------------------------------------------------------------------------
-- Start Activity
-----------------------------------------------------------------------------------------

function MaginotMission:StartActivity()
    print("START! -- MaginotMission:StartActivity()!");

    --Set the fight stage.
    self.FightStage = { NOFIGHT = 0, DEFENDA = 1, DEFENDB = 2, RUN = 3 };
    self.CurrentFightStage = self.FightStage.NOFIGHT;

    --Front landing zone.
    self.attackLZ1 = SceneMan.Scene:GetArea("LZ Team 2");

    --Back sneaky entrance.
    self.attackLZ2 = SceneMan.Scene:GetArea("EnemySneakSpawn2");

    --Trigger zone for arrival of escape craft.
    self.RescueTrigger = SceneMan.Scene:GetArea("RescueTrigger");

    --Zone for the escape craft to land in.
    self.RescueLZ = SceneMan.Scene:GetArea("RescueArea");

    --This times the round.
    self.RoundTimer = Timer();

    --How long to wait between spawns.
    self.SpawnTimer = Timer();

    --The escape ship, currently non-existent.
    self.EscapeShip = nil;

    --Stores who has died.
    self.braindead = {};

    --Stores the brain's ideal frozen position.
    self.spawnPos = {};

    for player = 0, self.PlayerCount - 1 do
        -- Check if we already have a brain assigned
        if not self:GetPlayerBrain(player) then        -- Place the brains.
	    self.braindead[player] = false;
	    --Create the brain.
	    local brain = CreateAHuman("Brain Robot");
	    --Move the brain to the right spot.
	    brain.Pos = Vector(2328 + player * 24,1240);
	    --Store this position.
	    self.spawnPos[player] = brain.Pos;
	    --Equip the brain with a pistol.
	    brain:AddInventoryItem(CreateHDFirearm("Pistol","Coalition.rte"));
	    --Set the brains to players.
            self:SetPlayerBrain(brain, player);
	    --Set the default landing zone.
            self:SetLandingZone(self:GetPlayerBrain(player).Pos, player);
            -- Set the observation target to the brain, so that if/when it dies, the view flies to it in observation mode
            self:SetObservationTarget(self:GetPlayerBrain(player).Pos, player);
            -- Let the spawn into the world, passing ownership
            MovableMan:AddActor(brain);
	    -- Set the brain to Sentry mode so it doesn't try to leave on you.
	    brain.AIMode = Actor.AIMODE_SENTRY;
	    self:ResetMessageTimer(player);
	    FrameMan:ClearScreenText(player);
        end
    end

    self.WList = { "Grenade Launcher", "Blaster", "Nailgun", "Rail Pistol", "Sniper Rifle", "Repeater", "Destroyer Cannon", "Annihiliator", "Nailer Cannon" };
    self.BList = { "Impulse Grenade" };
end

-----------------------------------------------------------------------------------------
-- Pause Activity
-----------------------------------------------------------------------------------------

function MaginotMission:PauseActivity(pause)
    print("PAUSE! -- MaginotMission:PauseActivity()!");
end

-----------------------------------------------------------------------------------------
-- End Activity
-----------------------------------------------------------------------------------------

function MaginotMission:EndActivity()
    print("END! -- MaginotMission:EndActivity()!");
end

-----------------------------------------------------------------------------------------
-- Update Activity
-----------------------------------------------------------------------------------------

function MaginotMission:UpdateActivity()
    --------------------------
    -- Iterate through all human players

    for player = 0, self.PlayerCount - 1 do
        -- The current player's team
        local team = self:GetTeamOfPlayer(player);
        
        -- Make sure the game is not already ending
        if not (self.ActivityState == Activity.OVER) then
            -- Check if any player's brain is dead
            local brain = self:GetPlayerBrain(player);
            if not brain or not MovableMan:IsActor(brain) or not brain:HasObjectInGroup("Brains") then
                self:SetPlayerBrain(nil, player);
                -- Try to find a new unasigned brain this player can use instead, or if his old brain entered a craft
                local newBrain = MovableMan:GetUnassignedBrain(team);
                -- Found new brain actor, assign it and keep on truckin'
                if newBrain and self.braindead[player] == false then
                    self:SetPlayerBrain(newBrain, player);
		    if MovableMan:IsActor(newBrain) then
                        self:SwitchToActor(newBrain, player, team);
		    end
                else                
                    FrameMan:SetScreenText("Your brain has been lost!", player, 333, -1, false);
		    self.braindead[player] = true;
                    -- Now see if all brains of self player's team are dead, and if so, end the game
		    local gameOver = true;
		    for player = 0, self.PlayerCount - 1 do
			if self.braindead[player] == false then
			    gameOver = false;
			end
		    end
                    if gameOver == true then
                        self.WinnerTeam = self:OtherTeam(team);
                        ActivityMan:EndActivity();
                    end
                    self:ResetMessageTimer(player);
                end
            else
                -- Update the observation target to the brain, so that if/when it dies, the view flies to it in observation mode
                self:SetObservationTarget(brain.Pos, player)
		-- If it's not time to escape yet, stop the brain from moving.
		if self.CurrentFightStage ~= self.FightStage.RUN then
		    local b = self:GetPlayerBrain(player);
		    b.Vel = Vector(0,0);
		    b.Pos = self.spawnPos[player];
		    b.AngularVel = 0;
		    b.RotAngle = 0;
		end
            end
        -- Game over, show the appropriate messages until a certain time
        elseif not self.GameOverTimer:IsPastSimMS(self.GameOverPeriod) then
-- TODO: make more appropriate messages here for run out of funds endings
            if team == self.WinnerTeam then
                FrameMan:SetScreenText("At least you survived...  But where are those dummies coming from?", player, 0, -1, false);
            else
                FrameMan:SetScreenText("Your brain has been lost!", player, 0, -1, false);
            end
        end
    end

    --Set up the AI modes once everything is spawned.
    if self.RoundTimer:IsPastSimMS(100) and self.RoundTimer:IsPastSimMS(1000) == false then
	for actor in MovableMan.Actors do
    	    actor.AIMode = Actor.AIMODE_SENTRY;
	end
    end
    --Check whether to advance the fight stage.
    if self.RoundTimer:IsPastSimMS(15000) and self.CurrentFightStage < self.FightStage.DEFENDA then
	--10 seconds before starting the fight.
	self.CurrentFightStage = self.FightStage.DEFENDA;
	for player = 0, self.PlayerCount - 1 do
            self:ResetMessageTimer(player);
	    FrameMan:ClearScreenText(player);
	    FrameMan:SetScreenText("DEFEND YOUR BASE AGAINST THE DUMMY ATTACK!", player, 1500, 9000, true);
	end
    elseif self.RoundTimer:IsPastSimMS(220000) and self.CurrentFightStage < self.FightStage.DEFENDB then
	--5 minutes in the enemies come through the back entrance.
	self.CurrentFightStage = self.FightStage.DEFENDB;
	for player = 0, self.PlayerCount - 1 do
            self:ResetMessageTimer(player);
	    FrameMan:ClearScreenText(player);
	    FrameMan:SetScreenText("CAUTION! MORE ENEMIES INCOMING FROM THE RIGHT SIDE ENTRANCE!", player, 1500, 9000, true);
	end
    elseif self.RoundTimer:IsPastSimMS(400000) and self.CurrentFightStage < self.FightStage.RUN then
	--10 minutes in, begin the escape.
	self.CurrentFightStage = self.FightStage.RUN;
	for player = 0, self.PlayerCount - 1 do
            self:ResetMessageTimer(player);
	    FrameMan:ClearScreenText(player);
	    if self.PlayerCount == 1 then
	        FrameMan:SetScreenText("DUMMIES ARE TOO OVERWHELMING! EVACUATE BUNKER IMMEDIATLY! GET YOUR BRAIN TO THE TOP OF THE BUNKER", player, 1500, 10000, true);
	    else
	        FrameMan:SetScreenText("DUMMIES ARE TOO OVERWHELMING! EVACUATE BUNKER IMMEDIATLY! GET ATLEAST ONE BRAIN TO THE TOP OF THE BUNKER", player, 1500, 10000, true);
	    end
	end
    end

    --Spawn enemies.
    if self.SpawnTimer:IsPastSimMS(5000) and MovableMan:GetMOIDCount() <= 240 then
	if self.CurrentFightStage >= self.FightStage.DEFENDA then
	    --Spawn 2 Dummies in a Dummy Drops Ship with a randomly-selected weapon, a digger, and maybe a grenade.
            local ship = CreateACDropShip("Drop Ship","Dummy.rte");
            local dummya = CreateAHuman("Dummy");
            local guna = CreateHDFirearm(self.WList[math.random(#self.WList)],"Dummy.rte");
            dummya:AddInventoryItem(guna);
            dummya:AddInventoryItem(CreateHDFirearm("Turbo Digger"));
	    if math.random() > 0.2 then
	        dummya:AddInventoryItem(CreateTDExplosive(self.BList[math.random(#self.BList)],"Dummy.rte"));
	    end
            ship:AddInventoryItem(dummya);
            local dummyb = CreateAHuman("Dummy");
            local gunb = CreateHDFirearm(self.WList[math.random(#self.WList)],"Dummy.rte");
            dummyb:AddInventoryItem(gunb);
            dummyb:AddInventoryItem(CreateHDFirearm("Turbo Digger"));
	    if math.random() > 0.2 then
	        dummya:AddInventoryItem(CreateTDExplosive(self.BList[math.random(#self.BList)],"Dummy.rte"));
	    end
            ship:AddInventoryItem(dummyb);
            -- See if there is a designated LZ Area for attackers, and only land over it
            if self.attackLZ1 then
                ship.Pos = Vector(self.attackLZ1:GetRandomPoint().X, 0);
            else
                -- Will appear anywhere when there is no designated LZ
                ship.Pos = Vector(SceneMan.Scene.Width * PosRand(), 0);
            end
            ship.Team = Activity.TEAM_2;
            ship:SetControllerMode(Controller.CIM_AI, -1);
            -- Let the spawn into the world, passing ownership
            MovableMan:AddActor(ship);
	end
	if self.CurrentFightStage >= self.FightStage.DEFENDB then
	    --Spawn a fully-equipped Dummy or a Dreadnought to sneak in from the right.
	    if MovableMan:GetMOIDCount() <= 240 then
		local actor = nil;
		local y = math.random();
		if y > 0.05 then
		    actor = CreateAHuman("Dummy");
		    actor.Team = Activity.TEAM_2;
		    actor.AIMode = Actor.AIMODE_BRAINHUNT;
		    actor:AddInventoryItem(CreateHDFirearm(self.WList[math.random(#self.WList)],"Dummy.rte"));
		    if math.random() > 0.1 then
			actor:AddInventoryItem(CreateTDExplosive(self.BList[math.random(#self.BList)],"Dummy.rte"));
		    end
		    actor:AddInventoryItem(CreateHDFirearm("Turbo Digger"));
		else
		    actor = CreateACrab("Dreadnought");
		    actor.Team = Activity.TEAM_2;
		    actor.AIMode = Actor.AIMODE_BRAINHUNT;
		end
		actor.Pos = Vector(SceneMan.Scene.Width - 6,self.attackLZ2:GetCenterPoint().Y);
		MovableMan:AddActor(actor);
	    end
	end
        -- Wait another period for next spawn
        self.SpawnTimer:Reset();
    end

    --Escape mechanism.  If the fight stage is the part where you must escape...
    if self.CurrentFightStage == self.FightStage.RUN then
	--For all players, do the following.
	for player = 0, self.PlayerCount - 1 do
	    --Make sure their brain is alive.
	    if self.braindead[player] == false then
		--If the player's brain is in the escape zone and the escape ship hasn't spawned yet...
		if self.RescueTrigger:IsInside(self:GetPlayerBrain(player).Pos) and not MovableMan:IsActor(self.EscapeShip) then
		    --Make a ship land in the escape zone.
		    self.EscapeShip = CreateACRocket("Rocket MK2");
		    self.EscapeShip.Pos = Vector(self.RescueLZ:GetRandomPoint().X, 0);
		    self.EscapeShip.Team = Activity.TEAM_1;
		    self.EscapeShip:SetControllerMode(Controller.CIM_AI, -1);
		    --Run through all players and give them a message that a ship is arriving.
		    for player = 0, self.PlayerCount - 1 do
        		self:ResetMessageTimer(player);
			FrameMan:ClearScreenText(player);
			FrameMan:SetScreenText("Sending down a ship...", player,  0, 5000, false);
		    end
		    MovableMan:AddActor(self.EscapeShip);
		end
	    end
	end
    end

    --OBJECTIVES
    --Clear the points, as they are re-added each frame.
    self:ClearObjectivePoints();

    for actor in MovableMan.Actors do
	--If a craft, for instance, has the brain, add the "Protect!" marker over it.
        if actor.PresetName == "Brain Robot" then
            self:AddObjectivePoint("Protect!", actor.AboveHUDPos, Activity.TEAM_1, GameActivity.ARROWDOWN);
        end
    end

    if self.CurrentFightStage == self.FightStage.RUN then
	self:AddObjectivePoint("Escape!", self.RescueLZ:GetCenterPoint() - Vector(0,32), Activity.TEAM_1, GameActivity.ARROWDOWN);
    end

    -- Sort the objective points
    self:YSortObjectivePoints();
end

-----------------------------------------------------------------------------------------
-- Craft Entered Orbit
-----------------------------------------------------------------------------------------

function MaginotMission:CraftEnteredOrbit()
    --If a craft leaves with the brain robot...
    if self.OrbitedCraft:HasObject("Brain Robot") then
	--Team 1 wins!
	self.WinnerTeam = Activity.TEAM_1;
	ActivityMan:EndActivity();
	--Tell the script to stop running for brains as the game has ended.
	for player = 0, self.PlayerCount - 1 do
	    self.braindead[player] = true;
	end
    end
end