class AutocraftSystem extends ScriptableSystem
{
	private var m_active : Bool;
	private var m_cycleDuration : Float;
	private var m_currentDelayID : DelayID;
	private var m_itemsUsed : array< ItemID >;

	private function OnSystemActivate( request : AutocraftActivateRequest )
	{
		var endCycleRequest : AutocraftEndCycleRequest;
		endCycleRequest = new AutocraftEndCycleRequest;
		if( m_active )
		{
			return;
		}
		m_active = true;
		m_currentDelayID = GameInstance.GetDelaySystem( GetGameInstance() ).DelayScriptableSystemRequest( 'AutocraftSystem', endCycleRequest, m_cycleDuration );
	}

	private function OnSystemDeactivate( request : AutocraftDeactivateRequest )
	{
		if( !( m_active ) )
		{
			return;
		}
		m_active = false;
		if( request.resetMemory )
		{
			m_itemsUsed.Clear();
		}
		GameInstance.GetDelaySystem( GetGameInstance() ).CancelDelay( m_currentDelayID );
	}

	private function OnCycleEnd( request : AutocraftEndCycleRequest )
	{
		var endCycleRequest : AutocraftEndCycleRequest;
		var itemsToAutocraft : array< ItemID >;
		var i : Int32;
		endCycleRequest = new AutocraftEndCycleRequest;
		if( !( m_active ) )
		{
			return;
		}
		itemsToAutocraft = GetItemsToAutocraft();
		for( i = 0; i < itemsToAutocraft.Size(); i += 1 )
		{
			GameInstance.GetTransactionSystem( GetGameInstance() ).GiveItem( GameInstance.GetPlayerSystem( GetGameInstance() ).GetLocalPlayerMainGameObject(), itemsToAutocraft[ i ], 1 );
			m_itemsUsed.Erase( m_itemsUsed.FindLast( itemsToAutocraft[ i ] ) );
			GameInstance.GetActivityLogSystem( GetGameInstance() ).AddLog( ( "Flathead autocrafted item " + TDBID.ToStringDEBUG( ItemID.GetTDBID( itemsToAutocraft[ i ] ) ) ) + "." );
		}
		m_currentDelayID = GameInstance.GetDelaySystem( GetGameInstance() ).DelayScriptableSystemRequest( 'AutocraftSystem', endCycleRequest, m_cycleDuration );
	}

	private function GetItemsToAutocraft() : array< ItemID >
	{
		var itemsToAutocraft : array< ItemID >;
		var i : Int32;
		for( i = 0; i < m_itemsUsed.Size(); i += 1 )
		{
			if( !( itemsToAutocraft.Contains( m_itemsUsed[ i ] ) ) )
			{
				itemsToAutocraft.PushBack( m_itemsUsed[ i ] );
			}
		}
		return itemsToAutocraft;
	}

	private export function OnItemUsed( request : RegisterItemUsedRequest )
	{
		var itemTags : array< CName >;
		if( !( m_active ) )
		{
			return;
		}
		itemTags = TweakDBInterface.GetItemRecord( ItemID.GetTDBID( request.itemUsed ) ).Tags();
		if( itemTags.Contains( 'Quest' ) )
		{
			return;
		}
		m_itemsUsed.PushBack( request.itemUsed );
	}

}

class AutocraftActivateRequest extends ScriptableSystemRequest
{
}

class AutocraftDeactivateRequest extends ScriptableSystemRequest
{
	var resetMemory : Bool;
}

class AutocraftEndCycleRequest extends ScriptableSystemRequest
{
}

class RegisterItemUsedRequest extends ScriptableSystemRequest
{
	var itemUsed : ItemID;
}

