//a wrapper that adds functionality to playing sfx.
//Due to script limitation for arrays, im using queues. 
//due to limitation with the cs numbers. Once it reaches a certain number it will fuck up.

exec("~/client/queue.cs");

//Allows callback back the sfxMaster when status changed
function SFXSource::onStatus( %this, %status )  
{  
   if ( %status $= "stopped" )  
      $sfxMaster.endPlayCallBack(%this);
}  

$sfxMaster = new ScriptObject(SfxMaster)
{
	sfxCh = 0;
	sfxGroup = new ScriptObject(Queue)
	{
	};
};

function SfxMaster::play(%this, %soundProfile)
{
	%sound = sfxPlay(%soundProfile);
	%sound.groupeRef = %this.sfxGroup.addEnd(%sound);
}

function SfxMaster::endPlayCallBack(%this, %sfxSource)
{
	%this.sfxGroup.deNode(%sfxSource.groupeRef);
}

function SfxMaster::pauseAll(%this)
{
	
}

function SfxMaster::stopAll(%this)
{
	sfxStopAll();
	%this.sfxGroup.delete();
	%this.sfxGroup = new ScriptObject(Queue){};
}

function SfxMaster::flagAsUsed(%this,%chNb)
{
    %this.sfxCh = %this.sfxCh | %chNb;
}

function SfxMaster::flagAsUnsed(%this,%chNb)
{
	echo("===="@%this.sfxCh);
	echo("======"@~%chNb);
    %this.sfxCh = %this.sfxCh & (~%chNb);
	echo("====="@%this.sfxCh);
}

function SfxMaster::findFreeSound(%this)
{
	echo (%this.sfxCh);
	//16 bit level
	for (%u = 0 ; %u < 2; %u++) //32 bit total. could increase it.
	{
		//clamp the value to 0x40000000
		%check = (~0x40000000 | %this.sfxCh) >> (%u * 16);
		if ((%check & 0xffff) !$= 0xffff) //Check if there is free space in the first 16 bit.
		{
			for (%i = 0 ; %i < 2; %i++)
			{
				%check = %this.sfxCh >> (8 * %i) >> (%u * 16);
				//8 bit level
				if (%check !$= 0xff)
				{
					for (%y = 0 ; %y < 2; %y++)
					{
						%check = %this.sfxCh >> (4 * %y) >> (8 * %i) >> (%u * 16);
						if (%check !$= 0xf) //check if the 4 bits have free space.
						{
							for (%z = 1; %z <=15; %z++)
							{
								if ((%check & %z) !$= %z)
								{
									return  ((%z << (4 * %y)) << (8 * %i)) << (%u * 16);
								}
							}
						}
					}
				}
			}
		}
	}
	return -1;
}
$sfxMaster.play(SwingSoundSwatMinigame);
//exec("~/client/sfxMaster.cs")
//echo($sfxMaster.findFreeSound())
//$sfxMaster.flagAsUsed(1)
//$sfxMaster.flagAsUnsed(1)