#include extreme\_ex_weapons;

unfix_turrets_init()
{
	num = 0;
	//get all the turrets on map and monitor them
	turrets = getentarray("misc_turret", "classname");
	for(i = 0; i < turrets.size; i++)	
	{	
		if(isDefined(turrets[i])) 
		{
			level.turret_origin[num] = turrets[i].origin;
			level.turret_model[num] = turrets[i].model;
			level.turret_name[num] = turrets[i].name;
			level.turret_angles[num] = turrets[i].angles;
			turrets[i].id = num;
			num ++;
			turrets[i].overheat = 0;
			turrets[i].ammo = 250;
			turrets[i] thread turret_think();
		}
	}
	turrets = getentarray("misc_mg42", "classname");
	for(i = 0; i < turrets.size; i++)	
	{	
		if(isDefined(turrets[i])) 
		{
			level.turret_origin[num] = turrets[i].origin;
			level.turret_model[num] = turrets[i].model;
			level.turret_name[num] = turrets[i].name;
			level.turret_angles[num] = turrets[i].angles;
			turrets[i].id = num;
			num ++;
			turrets[i].overheat = 0;
			turrets[i].ammo = 250;
			turrets[i] thread turret_think();
		}
	}
}

turret_think()
{
	level endon("ex_gameover");

	self.overheat = 0;
	while (1)
	{
		//wait for player to press the use button to use turret
		self waittill ("trigger",other);
		if(isPlayer(other))
		{	
			other.onturret = true;
			if(isDefined(other.ex_binocular_hint)) other.ex_binocular_hint.alpha = 0;
			if(level.ex_turrets == 2 && isPlayer(other) && !other has_turret())
			{	
				msg = &"TURRET_MELEE_TO_PICKUP";
				other show_hud(msg);
				if(isdefined(other.hasturret)) other.hasturret = undefined;
			}	
			else if(isPlayer(other) && other has_turret())
				other.hasturret = true;			
			
			wait .5;
			overheat = 0;
			
			for(;;)
			{
				wait .1;
				//wait for player to press melee button
				if(level.ex_turrets == 2 && isdefined(other) && other meleeButtonPressed() && !isdefined(other.hasturret))
				{	
					other turret_unfix(self);
					if(isdefined(other.hasturret)) other.hasturret = undefined;
					other.onturret = undefined;
					break;
				}
				//player is just getting off turret
				if(isdefined(other) && other useButtonPressed() || isdefined(other) && other isonground())
				{	
					other.onturret = undefined;
					other clear_hud();
					if(isDefined(other.ex_binocular_hint)) other.ex_binocular_hint.alpha = 1;
					if(isdefined(other.hasturret))	other.hasturret = undefined;
					break;
				}
				
				//if(overheat > 0) overheat --;
				//
				//while(isdefined(other) && other attackButtonPressed()) 
				//{	
				//	wait .1;
				//	overheat = overheat + 2;
				//	if(overheat > 100) 
				//		earthquake(overheat/400, .1, self.origin, 60);
				//	if(overheat > 150) 
				//		other suicide();
				//	
				//}
			
			}
		}
	}
}

turret_unfix(turret)
{
	self endon("disconnect");
	self endon("ex_dead");
	
	self playLocalSound("MP_bomb_plant");
	msg = &"TURRET_DEPLANT";
	self show_hud(msg);
	self disableweapon();
	wait 2;
	self clear_hud();
	newwep = "mobile_mg42";
	if(turret.model == "xmodel/weapon_30cal") newwep = "mobile_30cal"; 
	self.turretid = turret.id;
	turret delete();
	self enableweapon();
	cslot = self current_slot();
	self dropCurrentWeapon();
	self setWeaponSlotWeapon(cslot, newwep);
	return;
}	

mobile_mg()
{
	level endon("ex_gameover");

	self endon("disconnect");
	self endon("ex_dead");

	self.onturret = undefined;
	self.hasturret = undefined;
	self.turretid = undefined;
	count = 0;
	self.in_shoot_thread = false;
	//self thread test();
	while(isDefined(self) && isalive(self) && self.sessionstate == "playing")
	{
		wait .1;
		if(isDefined(self.turretid)) self thread has_fixed(); 
		if(isDefined(self) && is_turret() && !near_turret()) 
		{
			msg = &"TURRET_USE_SHOW_ICON";
			if(!isDefined(self.mst)) self show_hud(msg);
			
			for(;;)
			{
				wait .1;
				if(level.ex_mg_shoot_disable && isDefined(self) && self attackbuttonPressed() && !self.in_shoot_thread) self thread shoot_mon();
				
				if(isDefined(self) && self meleeButtonPressed() && is_turret() && !near_turret())
				{		
					if(count < 5) 
					{	
						count ++;
						continue;
					}
					count = 0;
					self clear_hud();
					wait .5;
					self turret_plant();
					self clear_hud();
					if(isDefined(self.turret_indicator)) self.turret_indicator destroy();
					break;
				}
				
				if(isDefined(self) && !is_turret() || near_turret())  
				{
					if(!isDefined(self.mst)) self clear_hud();
					break;
				}
			}
		}
	}
}

shoot_mon()
{
	level endon("ex_gameover");

	self endon("disconnect");
	self endon("ex_dead");

	cnt = 0;
	self.in_shoot_thread = true;
	while(self attackbuttonPressed() == true)
	{
		cnt ++;
		earthquake(.5, .2, self.ex_thumbmarker.origin, 50);
		if(level.ex_mg_shoot_damage)
			self thread [[level.callbackPlayerDamage]](self, self, 1, 1, "MOD_TRIGGER_HURT", "turret", undefined, (0,0,1), "none", 0);
		wait 0.2;
		if(cnt >= 3)
		{
			self disableWeapon ();
			wait 5;
			self enableWeapon ();
			break;
		}
		
		if(isDefined(self) && !is_turret())
			break;
	}
	self.in_shoot_thread = false;
}


turret_plant()	
{	
	level endon("ex_gameover");

	self endon("disconnect");
	self endon("ex_dead");

	self.mst = undefined;
	for(;;)
	{
		wait .01;
		if(isdefined(self.mst))	
		{
			self.mst --;
			if(self.mst <= 0) mst = undefined;
		}
			
		if(!isDefined(self.turret_indicator) && !near_turret()) self thread ShowTurretTarget();
		
		if(isDefined(self) && !self is_turret() || self near_turret())  
			return;
		
		if(isDefined(self) && !self meleeButtonPressed() && is_turret()) 
		{
			if(near_turret())
			{
				while(near_turret() && !is_turret())
				{
				wait .1;
				self.mst = 100;
				msg = &"TURRET_TOO_CLOSE_TURRET";
				self show_hud(msg);
				if(isDefined(self.turret_indicator)) self.turret_indicator destroy();
				}
				if(isDefined(self) && !is_turret())
					return;
			}
			
			trace = self GetEyeTrace();		
			
			if(distance(trace["position"],self.origin) < 20)
				return;
			
			if(distance(trace["position"],self.origin) > 60)
				return;
			origin = trace["position"];			
			startOrigin = origin;
			angles = self.angles;
			forward = anglesToForward((0,angles[1],0));
			forward = maps\mp\_utility::vectorScale( forward, 100000 );
			endOrigin = startOrigin + forward;
			trace = bulletTrace( startOrigin +(0,0,16), endOrigin +(0,0,16), false, self );
			if(distance(trace["position"],origin) < 20)
			{	
				self.mst = 100;
				msg = &"TURRET_TOO_CLOSE";
				self show_hud(msg);
				if(isDefined(self.turret_indicator)) self.turret_indicator destroy();
				return;
			}
			player_high_pos = self.origin;
			target_high_pos = (self.origin[0],self.origin[1],trace["position"][2]);
			high = distance(player_high_pos,target_high_pos);
			stance = "stand";
			dis = 50;
			if(high < 30) 
			{
				stance = "duck";
				dis = 80;
			}
			if(high < 20) 
			{
				stance = "prone";
				dis = 100;
			}
			leftarc = 0;
			rightarc = 0;
			mgang = angles[1] + 180;
			
			for(i = -10; i > -55; i--)
			{
				forward = anglesToForward((0,mgang + i,0));
				forward = maps\mp\_utility::vectorScale( forward, dis );
				endOrigin = Origin + forward;
				lng = distance(origin,endOrigin);
				trace = bulletTrace( origin + (0,0,16), endOrigin + (0,0,16), false, self );
				//test = spawn("script_model", (0,0,0));	
				//test setModel("xmodel/health_small");
				//test.origin = trace["position"] + (0,0,20);
				if(distance(trace["position"],origin + (0,0,16)) < lng)
					break;
				
				rightarc ++;
			}
			
			for(i = 10; i < 55; i++)
			{
				forward = anglesToForward((0,mgang + i,0));
				forward = maps\mp\_utility::vectorScale( forward, dis );
				endOrigin = Origin + forward;
				lng = distance(origin,endOrigin);
				trace = bulletTrace( origin + (0,0,16), endOrigin + (0,0,16), false, self );
				//test = spawn("script_model", (0,0,0));	
				//test setModel("xmodel/health_small");
				//test.origin = trace["position"] + (0,0,20);
				if(distance(trace["position"],origin + (0,0,16)) < lng)
					break;
				
				leftarc ++;
			}
			
			if(i < 12)
				return;
			
			msg = &"TURRET_PLANTING";
			self show_hud(msg);
			if(isDefined(self.turret_indicator)) self.turret_indicator destroy();
			self playLocalSound("MP_bomb_plant");
			cslot = self current_slot();
			model = self getcurrentweapon();
			newwep = "none";
			self setWeaponSlotWeapon(cslot, newwep);
			self.weapon["old" + cslot].name = newwep;
			self disableweapon();
			wait 2;
			typ = "30cal_" + stance + "_mp";
			xmod = "xmodel/weapon_30cal";
			if(model == "mobile_mg42") 
			{
				typ = "mg42_bipod_" + stance + "_mp";	
				xmod = "xmodel/weapon_mg42";
			}
			turret = spawnturret("misc_turret", origin, typ);
			turret setmodel(xmod);
			turret.angles = angles;
			turret SetTopArc(15);
			turret SetBottomArc(15);
			turret SetLeftArc(leftarc);
			turret SetRightArc(rightarc);
			turretid = undefined;
			if(isdefined(self.turretid)) turret.id = self.turretid;
			turret thread turret_think();
			self.turretid = undefined;
			self notify("spawn_turret");
			self enableweapon();
			self clear_hud();
			return;
		}
    }
}

near_turret()
{
	turrets = getentarray("misc_turret", "classname");
	for(i = 0; i < turrets.size; i++)	
	{
		if(isdefined(self) && isdefined(turrets[i]) && distance(turrets[i].origin,self.origin) < 100)	
			return true;
	}
	return false;
}

ShowTurretTarget() 
{	
	level endon("ex_gameover");

	self endon("disconnect");
	self endon("ex_dead");
	
	if(!isDefined(self.turret_indicator))
	{		
		self.turret_indicator = newClientHudElem(self);
		self.turret_indicator.name = "turretIndicator";
		self.turret_indicator.x = -1000;
		self.turret_indicator.y = -1000;
		self.turret_indicator.z = -1000;
		self.turret_indicator.alpha = .8;
		self.turret_indicator.archived = true;
		self.turret_indicator setShader("objpoint_star", 4, 4);
		self.turret_indicator setwaypoint(false);
	}

	for(;;) 
	{
		wait .01;
		if(!isDefined(self.turret_indicator)) 
			break;
		
		trace = self GetEyeTrace();
		if ( trace["fraction"] == 1.0 || trace["surfacetype"] == "default" || distance(trace["position"],self.origin) < 20 || distance(trace["position"],self.origin) > 60)
		{		
			if(!isDefined(self.mst) && distance(trace["position"],self.origin) < 20)
			{
				msg = &"TURRET_TOO_CLOSE";
				self show_hud(msg);
			}

			if(!isDefined(self.mst) && distance(trace["position"],self.origin) > 60)
			{
				msg = &"TURRET_TOO_FAR";
				self show_hud(msg);
			}

			self.turret_indicator.x = -1000;
			self.turret_indicator.y = -1000;
			self.turret_indicator.z = -1000;
		}
		else
		{
			self.turret_indicator.archived = true;
			self.turret_indicator setShader("objpoint_star", 4, 4);
			self.turret_indicator setwaypoint(false);
			self.turret_indicator.x = trace["position"][0];
			self.turret_indicator.y = trace["position"][1]; //- 5;
			self.turret_indicator.z = trace["position"][2] + 9;
			msg = &"TURRET_MELEE_TO PLANT";
			if(!isDefined(self.mst)) self show_hud(msg);
		}
	}
}

GetEyeTrace() 
{
	self endon("disconnect");
	self endon("ex_dead");

	startOrigin = self getEye() + self getPlayerEyeOffset();
	forward = anglesToForward( self getplayerangles() );
	forward = maps\mp\_utility::vectorScale( forward, 100000 );
	endOrigin = startOrigin + forward;

	trace = bulletTrace( startOrigin, endOrigin, false, self );
	
	return trace;
}

getPlayerEyeOffset() 
{
	self endon("disconnect");
	self endon("ex_dead");
	
	offset = (0,0,18);
    self.stance = [[level.ex_getStance]](false);
	
	if(self.stance == 1) offset = (0,0,2);
	if(self.stance == 2) offset = (0,0,-27);
	
	return offset;
}

show_hud(msg)
{
	self endon("disconnect");
	self endon("ex_dead");
		
	if(!isdefined(self.turret_msg))
	{
		self.turret_msg = newClientHudElem(self);
		self.turret_msg.alignX = "center";
		self.turret_msg.alignY = "middle";
		self.turret_msg.x = 320;
		self.turret_msg.y = 422;
		self.turret_msg.alpha = 1;
		self.turret_msg.fontScale = 1;
		self.turret_msg.sort = 1;
		self.turret_msg setText(msg);
	}	
		
	if(isdefined(self.turret_msg))
		self.turret_msg setText(msg);
	
	return;
}

clear_hud()
{
	self endon("disconnect");
	self endon("ex_dead");
		
	if(isdefined(self.turret_msg)) self.turret_msg destroy();
}

current_slot()
{
	current = self getCurrentWeapon();
	primary = self whatsInSlot("primary");
	primaryb = self whatsInSlot("primaryb");
	if(current == primary || primaryb == "ignore" || primary == "mobile_30cal" || primary == "mobile_mg42")
		return "primary";
	else
		return "primaryb";
}

is_turret()
{
	current = self getcurrentweapon();
	if(current == ("mobile_30cal") || current == ("mobile_mg42"))
		return true;
	else 
		return false;
}

has_turret()
{
	//chk if they have mobile_mg
	current = self getcurrentweapon();
		
	if(current == ("mobile_30cal") || current == ("mobile_mg42"))
		return true;
	if(self.weapon["primary"].name == ("mobile_30cal") || self.weapon["primary"].name == ("mobile_mg42"))
		return true;
	if(self.weapon["primaryb"].name == ("mobile_30cal") || self.weapon["primaryb"].name == ("mobile_mg42"))
		return true;
	else 
		return false;
}

has_fixed()
{
	self thread dead();
	self thread disconnected();
	self waittill("spawn_turret");
	if(isdefined(self.turretid))
	{
		origin = level.turret_origin[self.turretid];
		model = level.turret_model[self.turretid];
		name = level.turret_name[self.turretid];
		angles = level.turret_angles[self.turretid];
		typ = "30cal_stand_mp";
		if(model == "xmodel/weapon_mg42") 
			typ = "mg42_bipod_stand_mp";	
		turret = spawnturret("misc_turret", origin, typ);
		turret setmodel(model);
		turret.angles = angles;
		turret SetTopArc(15);
		turret SetBottomArc(15);
		turret SetLeftArc(45);
		turret SetRightArc(45);
		turret.id = self.turretid;
		turret thread turret_think();
		self.turretid = undefined;
	}
}

dead()
{
	self waittill("ex_dead");
	self notify("spawn_turret");
}

disconnected()
{
	self waittill("disconnect");
	self notify("spawn_turret");
}

test()
{
	for(;;)
	{
		wait 5;
		//if(isDefined(self)) iprintln(&"current",self.weapon["current"].name); 	
		//if(isDefined(self)) iprintln(&"primary",self.weapon["primary"].name);
		//if(isDefined(self)) iprintln(&"secondary",self.weapon["primaryb"].name);
		//if(isDefined(self)) iprintln(&"virtual",self.weapon["virtual"].name);
		//if(isDefined(self)) iprintln(&"oldprimary",self.weapon["oldprimary"].name);
		if(isDefined(self.onturret)) iprintln(&"ON TURRET");
		if(!isDefined(self.onturret)) iprintln(&"OFF TURRET");
	}
}
