#include maps\mp\_utility;
#include maps\mp\gametypes\_hud_util;
#include common_scripts\utility;
#include maps\mp\_audio;
#include maps\mp\gametypes\_horde_zombies;

main()
{
	//SetLightingState(1);
	maps\mp\mp_prison_z_precache::main();
	maps\createart\mp_prison_z_art::main();
	maps\mp\mp_prison_z_fx::main();
	maps\mp\mp_prison_z_lighting::main();
	maps\mp\_load::main();
	
//	AmbientPlay( "ambient_mp_setup_template" );

	maps\mp\_compass::setupMiniMap( "compass_map_mp_prison" );	

	setdvar( "r_lightGridEnableTweaks", 1 );
	setdvar( "r_lightGridIntensity", 1.33 );
	
	game["attackers"] = "allies";
	game["defenders"] = "axis";
	
	level.mapCustomKillstreakFunc = ::prisonCustomKillstreakFunc;
	
//	thread set_lighting_values(); // after maps\mp\_load::main();
	
	thread ambientAnimation();
	thread zombieExtractionGates();
	thread initZombies();
	
	while (true)
    {
        level waittill("connected", player);               // we need to set the dvars for each player as he connects.

        skybox_night = GetEntArray("prsion_night_sky", "targetname");
		foreach( thing in skybox_night )
		{
			thing hide();
		}
        
        level waittill ( "zombie_go_night" );
        
      	//player SetClutOverrideDisableForPlayer ( 0 );
      	//SetLightingState(2);
      	skybox_night = GetEntArray("prsion_night_sky", "targetname");
		foreach( thing in skybox_night )
		{
			thing show();
		}
		
		foreach ( player in level.players )
		{
			player LightSetForPlayer( "mp_prison_night" );
			player SetClientTriggerVisionSet( "mp_prison_night", 1.0 );
			if ( level.nextgen )
			{
				//player SetClutOverrideDisableForPlayer( 0 );
				//wait 0.1;
				player SetClutOverrideEnableForPlayer( "clut_identity", 0 );
			}
		}
        
	}
}

prisonCustomKillstreakFunc()
{
	//level thread maps\mp\killstreaks\streak_mp_prison::init();
}

set_lighting_values()
{
    if ( IsUsingHDR() )
    {     
    	while (true)
        {
            level waittill("connected", player);               // we need to set the dvars for each player as he connects.
            player SetClientDvars(
                "r_tonemap", "1",
                "r_tonemapkey", "0"              
           );
            //player SetClutOverrideEnableForPlayer( "clut_mp_prison_z_day", 1 );
            /*
            player SetClientDvars(
                "r_tonemap", "1",
                "r_tonemapadaptspeed", ".07",
                "r_tonemapkey", "0",
                "r_veil", "1",
                "r_veilstrength", ".087",
                "r_tonemapexposure", "-10" 
                
              );
            
            //For setting the max exposure so we can get contrast back into the map without blowing everything out
            setdvar ("r_tonemapmaxexposure", "-10");
            
            //Controling how much SSAO there is in the scene
//            setdvar ("r_ssaoPower", "3.5");
//            setdvar ("r_ssaoBlurRadius", "1.5");

		setDvar("r_ssaoPower", "12.0");
		setDvar("r_ssaoStrength", "0.45");
		setDvar("r_ssaominstrengthdepth", "25.0");
		setDvar("r_ssaomaxstrengthdepth", "40.0");
            
            
//        setdvar("r_tonemapkey", .029, 3.0 );
        setDvar("r_tonemapkeydark", .001, 1.0 );
  		setDvar("r_tonemapkeydarklum", 3, 1.0);
  		setDvar("r_tonemapkeylight", .05, 1.0);
  		setDvar("r_tonemapkeylightlum", 20, 1.0);
  		*/
            
        }
    }
}

ambientAnimation()
{
	radar_dishes = GetEntArray( "guard_tower_radar", "targetname" );
	
	foreach( dish in radar_dishes )
	{
		dish thread rotateRadar();
	}
}

rotateRadar()
{
	if ( !IsDefined( level.rotatetime ) )
	{
		level.rotatetime = 20;
	}
	
	while( 1 )
	{
		self RotateVelocity( ( 0, -100, 0 ), level.rotatetime ); // set a rotation velocity for a 20sec duration instead of asking the radars to rotate 180 degrees every second => save a lot of bandwidth !!
		wait level.rotatetime;
	}
}

zombieExtractionGates()
{
	level.zombieMovingGates = [];
	level.zombieRotatingGates = [];
	
	moveTime = .5;
	
	extractionGates = GetEntArray( "extraction_gate", "targetname" );
	
	foreach( gate in extractionGates )
	{
		gate_struct = SpawnStruct();
		gate.originalPos = gate.origin;
		gate_struct.gate = gate;
		
		moveToOrg = getstruct( gate.target, "targetname" );
		gate_struct.dest = moveToOrg;
			
		col = getent( moveToOrg.target, "targetname" );
		col.originalPos = col.origin;
		gate_struct.collision = col;

		level.zombieMovingGates[ level.zombieMovingGates.size ] = gate_struct;
	}
	
	foreach( gate in level.zombieMovingGates )
	{
		gate.gate moveto( gate.dest.origin, moveTime, .1, .2 );
		gate.collision moveto( gate.dest.origin, moveTime, .1, .2 );
	}
	
	wait 1.0;
	
	thread disconnectGatePaths();

	level waittill ( "start_extraction" );
	
	foreach( gate in level.zombieMovingGates )
		gate.collision connectpaths();
	
	foreach( gate in level.zombieMovingGates )
	{
		gate.gate moveto( gate.gate.originalPos, moveTime, .1, .2 );
		gate.collision moveto( gate.gate.originalPos, moveTime, .1, .2 );
	}
	
}

disconnectGatePaths()
{
	level endon ( "game_ended" );
	
	level waittill ( "start_round" );
	
	wait 5;
	
	foreach( gate in level.zombieMovingGates )
		gate.collision disconnectpaths();
	

}

bounceGate( delaytime )
{
	self endon( "stop_bounce" );
	
	thread gateFxOn();
	wait delaytime;
	thread gateFxOff();
	
	forward = anglesToForward( VectorToAngles( self.dest.origin - self.gate.originalPos ) );
	
	bounceDistForward = forward * 2;
	
	while( 1 )
	{
		bounceForwardTime = RandomfloatRange( .1, .5 );
		bounceBackTime = RandomfloatRange( .1, .5 );
		
		thread gateFxOn();
		self.gate moveto( self.gate.origin + bounceDistForward, bounceForwardTime, .05, .05 );
		
		wait bounceForwardTime;
		
		self.gate moveto( self.dest.origin, bounceBackTime, .05, .05 );
		
		wait bounceBackTime;
		
		thread gateFxOff();
		
		wait RandomFloat( 2 );
	}
}

gateFxOn()
{
	self endon( "stop_sparks" );
	while( 1 ) 
	{
		foreach( fx in self.sparks )
		{
			PlayFXonTag( getfx( level.gate_spark_fx ), fx, "tag_origin" );
		}
		wait randomFloatRange(0.5, 1.0);
	}
}

gateFxOff()
{
	self notify( "stop_sparks" );
	foreach( fx in self.sparks )
	{
		stopFXonTag( getfx( level.gate_spark_fx ), fx, "tag_origin" );
	}
}
	
//---- FUNCTIONALITY ----//

onPlayerConnect()
{
	for ( ;; )
	{
		level waittill ( "connected", player );
			player.numAreas = 0;
	}
}

playerEnterArea( trigger )
{
	self.numAreas++;
	
	if ( self.numAreas == 1 )
		self gasEffect();
}


playerLeaveArea( trigger )
{
	//TODO:need to call playerLeaveArea when the killstreak is over on anyone who was in the trigger.
	self.numAreas--;
	assert( self.numAreas >= 0 );
	
	if ( self.numAreas != 0 )
		return;
	
	self.poison = 0;
	self notify( "leftTrigger");
	
	if ( isDefined( self.gasOverlay ) )
		self.gasOverlay fadeoutBlackOut( .10, 0 );
}

gasFieldsOn()
{
	gasFields = getentarray("gas_trigger", "targetname");
	
	foreach( trigger in gasFields )
	{
		trigger trigger_on();
	}
	
}

gasFieldsOff()
{
	gasFields = getentarray("gas_trigger", "targetname");
	
	foreach( trigger in gasFields )
	{
		trigger trigger_off();
	}
	
}

soundWatcher( soundOrg )
{
	self waittill_any( "death", "leftTrigger" );
	
	self stopLoopSound();
}

gasEffect()
{
	self endon( "disconnect" );
	self endon( "game_ended" );
	self endon( "death" );
	self endon( "leftTrigger" );
	
	self.poison = 0;
	self thread soundWatcher( self );
	
	while (1)
	{
		self.poison ++;
		
		switch( self.poison )
		{
			case 1:				  
//				self.radiationSound = "item_geigercouner_level2";
//				self playLoopSound( self.radiationSound );
				self ViewKick( 1, self.origin );
				break;
			case 3:				  
				self shellshock( "mp_prison_gas", 4);
//				self.radiationSound = "item_geigercouner_level3";
//				self stopLoopSound();
//				self playLoopSound( self.radiationSound );
				self ViewKick( 3, self.origin );
				self doGasDamage(25);
				break;
			case 4:
				self shellshock( "mp_prison_gas", 5);
//				self.radiationSound = "item_geigercouner_level3";
//				self stopLoopSound();
//				self playLoopSound( self.radiationSound );
				self ViewKick( 15, self.origin );
				self thread blackout();
				self doGasDamage(45);
				break;
			case 6:
				self shellshock( "mp_prison_gas", 5);
				//self.radiationSound = "item_geigercouner_level4";
				//self stopLoopSound();
				//self playLoopSound( self.radiationSound );
				self ViewKick( 75, self.origin );
				self doGasDamage(80);
				break;
			case 8:
				self shellshock( "mp_prison_gas", 5);
//				self.radiationSound = "item_geigercouner_level4";
//				self stopLoopSound();
//				self playLoopSound( self.radiationSound );
				self ViewKick( 127, self.origin );
				self doGasDamage(175);

				break;
		}
		wait(1);
	}
	wait(5);
}

blackout( )
{
	self endon( "disconnect" );
	self endon( "game_ended" );
	self endon( "death" );
	self endon( "leftTrigger" );

	if ( !isDefined( self.gasOverlay ) )
	{
		self.gasOverlay = newClientHudElem( self );
		self.gasOverlay.x = 0;
		self.gasOverlay.y = 0;
		self.gasOverlay setshader( "black", 640, 480 );
		self.gasOverlay.alignX = "left";
		self.gasOverlay.alignY = "top";
		self.gasOverlay.horzAlign = "fullscreen";
		self.gasOverlay.vertAlign = "fullscreen";
		self.gasOverlay.alpha = 0;
	}

	min_length = 1;
	max_length = 2;
	min_alpha = .25;
	max_alpha = 1;

	min_percent = 5;
	max_percent = 100;

	fraction = 0;

	for ( ;; )
	{
		while ( self.poison > 1 )
		{
			percent_range = max_percent - min_percent;
			fraction = ( self.poison - min_percent ) / percent_range;

			if ( fraction < 0 )
				fraction = 0;
			else if ( fraction > 1 )
				fraction = 1;

			length_range = max_length - min_length;
			length = min_length + ( length_range * ( 1 - fraction ) );

			alpha_range = max_alpha - min_alpha;
			alpha = min_alpha + ( alpha_range * fraction );

			end_alpha = fraction * 0.5;

			if ( fraction == 1 )
				break;

			duration = length / 2;

			self.gasOverlay fadeinBlackOut( duration, alpha );
			self.gasOverlay fadeoutBlackOut( duration, end_alpha);

			// wait a variable amount based on self.radiation.totalpercent, this is the space in between pulses
			//wait 1;
			wait( fraction * 0.5 );
		}

		if ( fraction == 1 )
			break;

		if ( self.gasOverlay.alpha != 0 )
			self.gasOverlay fadeoutBlackOut( 1, 0);

		wait 0.05;
	}
	self.gasOverlay fadeinBlackOut( 2, 0);
}

doGasDamage( iDamage )
{
	//if( !isdefined( level.mp_prison_killstreak.owner ) )
	//	return;
	
	//TODO:Handle friendly fire
	self thread [[ level.callbackPlayerDamage ]](
	self,// eInflictor The entity that causes the damage.( e.g. a turret )
	self,// eAttacker The entity that is attacking.
	iDamage,// iDamage Integer specifying the amount of damage done
	0,// iDFlags Integer specifying flags that are to be applied to the damage
	"MOD_SUICIDE",// sMeansOfDeath Integer specifying the method of death
	"mp_prison_gas",// sWeapon The weapon number of the weapon used to inflict the damage
	self.origin,// vPoint The point the damage is from?
	( 0,0,0 ) - self.origin,// vDir The direction of the damage
	"none",// sHitLoc The location of the hit
	0// psOffsetTime The time offset for the damage
	);
}

fadeinBlackOut( duration, alpha )
{
	self fadeOverTime( duration );
	self.alpha = alpha;
	wait duration;
}

fadeoutBlackOut( duration, alpha )
{
	self fadeOverTime( duration );
	self.alpha = alpha;
	wait duration;
}

