#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#import "ETSocket.h"

@implementation ETSocket
- (id) connectToRemoteHost:(NSString*)aHost forService:(NSString*)aService
{
	char * server = [aHost UTF8String];
	char * service = [aService UTF8String];
	struct addrinfo hints, *res, *res0;
	int error;
	NSString * errorCause = nil;

	memset(&hints, 0, sizeof(hints));
	hints.ai_family = PF_UNSPEC;
	hints.ai_socktype = SOCK_STREAM;
	//Ask for a stream address.
	error = getaddrinfo(server, service, &hints, &res0);
	if (error) 
	{
		errx(1, "%s", gai_strerror(error));
	}
	s = -1;
	for (res = res0; res != NULL && s < 0 ; res = res->ai_next) 
	{
		s = socket(res->ai_family, res->ai_socktype,
		res->ai_protocol);
		//If the socket failed, try the next address
		if (s < 0) 
		{
			continue;
		}
		//If the connection failed, try the next address
		if (connect(s, res->ai_addr, res->ai_addrlen) < 0) 
		{
			close(s);
			s = -1;
			continue;
		}
	}
	freeaddrinfo(res0);
	if (s < 0) 
	{
		err(1, "%s", cause);
	}
}

- (void) pushFilter:(id<ETSocketFilter>)aFilter
{
	[filters addObject:aFilter];
}
- (void) popFilter
{
	[filters removeLastObject];
}
- (unsigned char*) read
{
	int bytes = read(s, buffer, space);
	FOREACHI(filters, filter)
	{

	}
}
@end
