#include "FilterConnection.h"
template<class SAMPLE> 
FilterConnection<SAMPLE>::FilterConnection<SAMPLE>(BufferedFile file): inConnections() {
	init(file,"Unnamed");
	initBuffer();
}
template<class SAMPLE> 
FilterConnection<SAMPLE>::FilterConnection<SAMPLE>(BufferedFile file,string name): inConnections() {
	init(file,name);
	initBuffer();
}
template<class SAMPLE> 
void FilterConnection<SAMPLE>::initBuffer() {
	this.buffer = (void*)(new SAMPLE[BUFFSIZE]);
	this.buffer = (void*)(new SAMPLE[BUFFSIZE]);
}
template<class SAMPLE> 
void FilterConnection<SAMPLE>::connectFrom(Connection<SAMPLE> &conn) { // Accepts a connection FROM conn connection. 
	if (conn.readable()) {
		inConnections.push_back(conn);
	} else {
		throw new string("Not A Input Connection");
	}
}
template<class SAMPLE> 
void FilterConnection<SAMPLE>::process() {
	int i =0;
	int c = 0;
	int size = inConnections.size();
	vector<Connection<SAMPLE>*>::iterator iter;
	for (iter = inConnections.begin(); iter < inConnections.end(); iter++) {
		c++;
		*iter.read(this.buffer2,BUFFSIZE);
		for (i = 0; i < BUFFSIZE; i++ ) {
			this.buffer[i]+=this.buffer2[i]/size;
		}
	}
	if (c) {
		this.write(this.buffer,BUFFSIZE);
	}
}
template<class SAMPLE> 
FilterConnection<SAMPLE>::~FilterConnection<SAMPLE>() {
	destruct();
}
template<class SAMPLE> 
void FilterConnection<SAMPLE>::destruct() {
	delete  buffer;
	delete buffer2;
}
template<class SAMPLE> 
void FilterConnection<SAMPLE>::disconnectFrom(Connection<SAMPLE> & conn) { //Disconnects an incoming patch between the current 
	vector<Connection<SAMPLE>*>::iterator iter;
	for (iter = inConnections.begin(); iter < inConnections.end(); iter++) {
		if (*iter == &conn) {
			inConnections.erase(iter);
			break;
		}
	}
}
template<class SAMPLE> 
void FilterConnection<SAMPLE>::disconnectTo(Connection<SAMPLE> & conn) {//Disconnects an outgoing patch between current
	conn.disconnectTo(this);
}
template<class SAMPLE> 
string * FilterConnection<SAMPLE>::getXML() { //gets an XML string 
	string * out =new string("<connection><type>"+this->xmlType()+"</type><name>"+this->getName()+"</name><id>"+getFileHandle()+"</id></connection>\n");
	vector<Connection<SAMPLE>*>::iterator iter;
	for (iter = inConnections.begin(); iter < inConnections.end(); iter++) {
		(*out)+="<patch><from>"+(*iter)->getFileHandle()+"</from><to>"+getFileHandle()+"</to></patch>";
	}
	return out;
}
template<class SAMPLE> 
string  FilterConnection<SAMPLE>::xmlType() { //gets an XML string 
	return "FILTER";
}

