/*=============================================================================
	CAAUConnections.h
	
	$Log: CAAUConnections.cpp,v $
	Revision 1.3  2004/10/15 20:45:17  bills
	add an IsMember call
	
	Revision 1.2  2004/08/24 00:01:46  bills
	fix warnings
	
	Revision 1.1  2004/07/26 19:27:52  bills
	initial
	
	
	created Mon Jul 26, 2004 William Stewart
	Copyright (c) 2003 Apple Computer, Inc.  All Rights Reserved

	$NoKeywords: $
=============================================================================*/
#include "CAAUConnections.h"

OSStatus	CAAUConnections::Find (const AUGraph &inGraph, const CAAudioUnit &inUnit, AudioUnitScope inScope)
{
	if (!mConns.empty()) mConns.clear();

	AudioUnit theUnit;
	OSStatus result = AUGraphGetNodeInfo (inGraph, inUnit.GetAUNode(), NULL, NULL, NULL, &theUnit);
	if ((theUnit != inUnit.AU()) || result) return (result ? result : -1);
		
	UInt32 numConns = 0;
	if ((result = AUGraphCountNodeConnections (inGraph, inUnit.GetAUNode(), &numConns))) return result;
	
	if (numConns) {
		AudioUnitNodeConnection s_conns[4];
		AudioUnitNodeConnection *conns = (numConns > 4 ? new AudioUnitNodeConnection[numConns] : s_conns);
	
		require_noerr (result = AUGraphGetNodeConnections (inGraph, inUnit.GetAUNode(), conns, &numConns), home);
		
		for (unsigned int i = 0; i < numConns; ++i) {
			if (inScope == kAudioUnitScope_Output && conns[i].sourceNode == inUnit.GetAUNode()) {
				AudioUnit otherAU;
				require_noerr (result = AUGraphGetNodeInfo (inGraph, conns[i].destNode, NULL, NULL, NULL, &otherAU), home);
				mConns.push_back (AUConn (conns[i].sourceOutputNumber, otherAU, conns[i].destNode, conns[i].destInputNumber));
			}
			if (inScope == kAudioUnitScope_Input && conns[i].destNode == inUnit.GetAUNode()) {
				AudioUnit otherAU;
				require_noerr (result = AUGraphGetNodeInfo (inGraph, conns[i].sourceNode, NULL, NULL, NULL, &otherAU), home);
				mConns.push_back (AUConn (conns[i].destInputNumber, otherAU, conns[i].sourceNode, conns[i].sourceOutputNumber));
			}
		}
	home:
		if (numConns > 4) delete [] conns;
	}
	return result;
}
	
bool		CAAUConnections::Connection (UInt32				inIndex, 
									AudioUnitElement		&outMyEl, 
									CAAudioUnit				&outOtherAU, 
									AudioUnitElement		&outOtherAUEl)
{
	if (inIndex < Size()) {
		outMyEl = mConns[inIndex].mMyEl;
		outOtherAU = mConns[inIndex].mOtherAU;
		outOtherAUEl = mConns[inIndex].mOtherEl;
		return true;
	}
	return false;
}

bool		CAAUConnections::IsMember (AudioUnitElement inMyEl) const
{
	for (AUConns::const_iterator iter = mConns.begin(); iter < mConns.end(); ++iter) {
		const AUConn &conn = (*iter);
		if (inMyEl == conn.mMyEl);
			return true;
	}
	return false;
}

void		CAAUConnections::Print (FILE* file) const
{
	for (AUConns::const_iterator iter = mConns.begin(); iter < mConns.end(); ++iter) {
		const AUConn &conn = (*iter);
		fprintf (file, "El: %ld, To:", conn.mMyEl);
		conn.mOtherAU.Print (file);
		fprintf (file, ", Other El: %ld\n", conn.mOtherEl); 
	}
}