//****************************\\
//  This File is Copyright of \\
//     R&R Projects © 2006    \\
//****************************\\

init()
{
	if(!level.wwx_wepsonback || !level.wwx_wepo_secondary) return;
	level thread onPlayerConnect();
}

onPlayerConnect()
{
	for(;;)
	{
		level waittill("connecting", player);
		player thread onPlayerSpawned();
	}
}

onPlayerSpawned()
{
	self endon("disconnect");

	for(;;)
	{
		self waittill("spawned_player");
		self thread wobmonitor();
	}
}

wobmonitor()
{
	self endon("wwx_gameover");
	self endon("disconnect");
	self endon("wwx_dead");

	self.weapononback = undefined;
	wobactiveslot = "none";

	for(;;)
	{
		if(level.wwx_currentgt == "lib" && isDefined(self.in_jail) && self.in_jail) attach_enabled = false;
			else attach_enabled = true;

		current = self getcurrentweapon();

		if(current != "")
		{
			weapon1 = self getweaponslotweapon("primary");
			weapon2 = self getweaponslotweapon("primaryb");

			if(current == weapon1)
				currentslot = "primary";
			else
			{
				assert(current == weapon2);
				currentslot = "primaryb";
			}

			wait 0.05;

			if(currentslot != wobactiveslot)
			{
				wobactiveslot = currentslot;

				// If primary is active, put secondary weapon on back
				if(wobactiveslot == "primary")
				{
					if(isValidWeapon(weapon2))
					{
						if(isDefined(self.weapononback))
						{
							//logprint("Player " + self.name + " detaching primary weapon " + self.weapononback + " from back\n");
							self detach("xmodel/" + self.weapononback, "");
							self.weapononback = undefined;
						}
						
						if(attach_enabled)
						{
							self.weapononback = weapon2;
							//logprint("Player " + self.name + " attaching secondary weapon " + self.weapononback + " on back\n");
							self attach("xmodel/" + self.weapononback, "");
						}
					}
				}
				// If secondary is active, put primary weapon on back
				else if(wobactiveslot == "primaryb")
				{
					if(isValidWeapon(weapon1))
					{
						if(isDefined(self.weapononback))
						{
							//logprint("Player " + self.name + " detaching secondary weapon " + self.weapononback + " from back\n");
							self detach("xmodel/" + self.weapononback, "");
							self.weapononback = undefined;
						}

						if(attach_enabled)
						{
							self.weapononback = weapon1;
							//logprint("Player " + self.name + " attaching primary weapon " + self.weapononback + " on back\n");
							self attach("xmodel/" + self.weapononback, "");
						}
					}
				}
			}
		}
		
		wait 0.5;
	}
}

isValidWeapon(weapon)
{
	if(!isDefined(weapon)) return false;

	switch(weapon)
	{
		case "none":
		case "knife_mp":
		case "knive_mp":
		case "dummy1_mp":
		case "dummy2_mp":
		case "dummy3_mp":
		case "dummy4_mp":
		case "sprint_mp":
		case "ignore": return false;
	}

	return true;
}
