//
//  TuveConnection.m
//  Tuve
//
//  Created by Philippe Hausler on 9/8/08.
//  Copyright 2008 Philippe Hausler. All rights reserved.
//

#import "TuveConnection.h"
#import "TCPSocket.h"

@implementation TuveConnection
@synthesize tChannel;
- (id)init
{
	self = [super init];
	channelSocket = [[TCPSocket alloc] initWithConnectionTo:@"Ivorytower.UbixOnline.com" onTCPPort:9999];
	channelConnection = [[NSFileHandle alloc] initWithFileDescriptor:[channelSocket socket]];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dataAvailable:) name:NSFileHandleDataAvailableNotification object:NULL];
	[channelConnection writeData:[@"<policy-file-request/>\0" dataUsingEncoding:NSUTF8StringEncoding]];
	tChannel = @"#TUvé";
	login = @"Lenari";
	password = @"cynthiana12";
	protocolStage = TUWaitingForCrossDomainPolicy;
	[channelConnection waitForDataInBackgroundAndNotify];
	return self;
}
- (void)dataAvailable:(NSNotification *)aNotification
{
	NSData *packet = [channelConnection availableData];
	NSString *packetStr = [[[NSString alloc] initWithBytes:[packet bytes] length:[packet length] encoding:NSUTF8StringEncoding] autorelease];
	[self processString:packetStr];
	[[aNotification object] waitForDataInBackgroundAndNotify];
}
- (void)processString:(NSString *)packetStr
{
	NSArray *packets = [packetStr componentsSeparatedByString:@"\n"];
	if(buffer == NULL)
	{
		[buffer release];
	}
	if(![packetStr hasSuffix:@"\n"])
	{
		buffer = [[NSString stringWithString:[packets objectAtIndex:([packets count]-1)]] retain];
	}
	if(protocolStage == TUWaitingForCrossDomainPolicy)
	{
		[self sendVersion];
	}
	else
	{
		for(NSString *packet in packets)
		{
			NSLog(packet);
			NSArray *packetParts = [packet componentsSeparatedByString:@":"];
			if([packet hasPrefix:@"CLIENT"])
			{
				if([[packetParts objectAtIndex:1] isEqualToString:@"1"])
				{
					NSLog(@"Negotiation Error: %@", [packetParts objectAtIndex:2]);
				}
				else if([[packetParts objectAtIndex:1] isEqualToString:@"0"])
				{
					[self sendIdent];
				}
			}
			else if([packet hasPrefix:@"IDENT"])
			{
				if([[packetParts objectAtIndex:1] isEqualToString:@"1"])
				{
					NSLog(@"Identification Error: %@", [packetParts objectAtIndex:2]);
				}
				else if([[packetParts objectAtIndex:1] isEqualToString:@"0"])
				{
					[self joinChannel:tChannel];
				}
			}
			else if([packet hasPrefix:@"JOIN"])
			{
				if([[packetParts objectAtIndex:1] isEqualToString:@"ERROR"])
				{
					NSLog(@"Channel Error: %@", [packetParts objectAtIndex:2]);
				}
				else
				{
					[self login];
				}
			}
			else if([packet hasPrefix:@"MODE"])
			{
			}
			else if([packet hasPrefix:@"PING"])
			{
				[self pong];
			}
			else if([packet hasPrefix:@"CURPOS"])
			{
				NSString *movieURL = [NSString stringWithFormat:@"rtmp://rtmp.ubixonline.com/%@", [packetParts objectAtIndex:3]];
			}
			else if([packet hasPrefix:@"MSG"])
			{
				if([[packetParts objectAtIndex:2] isEqualToString:tChannel])
				{
					
					[[NSNotificationCenter defaultCenter] postNotificationName:@"TUMSG" 
																		object:self 
																	  userInfo:[NSDictionary dictionaryWithObjectsAndKeys:[packetParts objectAtIndex:1],@"sender", [packetParts objectAtIndex:2], @"channel", [packetParts objectAtIndex:3], @"message", NULL]];
				}
			}
		}
	}
}
- (void)sendVersion
{
	NSLog(@"Sending version");
	protocolStage = TUWaitingForVersionHandshake;
	[channelConnection writeData:[@"CLIENT 3.0\n" dataUsingEncoding:NSISOLatin1StringEncoding]];
	
}
- (void)sendIdent
{
	NSLog(@"Sending ident");
	NSString *ident = @"2151367332198";
	protocolStage = TUWaitingForIdentResponse;
	[channelConnection writeData:[[NSString stringWithFormat:@"IDENT %@:%@\n", login, ident] dataUsingEncoding:NSUTF8StringEncoding]];
	
}
- (void)joinChannel:(NSString *)channel
{
	NSLog(@"joining channel %@", channel);
	protocolStage = TUWaitingForChannelJoinResponse;
	[channelConnection writeData:[[NSString stringWithFormat:@"JOIN %@\n", channel] dataUsingEncoding:NSUTF8StringEncoding]];
}
- (void)login
{
	NSLog(@"logging in");
	
	protocolStage = TUIde;
	[channelConnection writeData:[[NSString stringWithFormat:@"MODE tuvebot:LOGIN %@ %@\n", login, password] dataUsingEncoding:NSUTF8StringEncoding]];
}
- (void)pong
{
	[channelConnection writeData:[[NSString stringWithFormat:@"PONG!\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}
- (void)sendChat:(NSString *)chat toChannel:(NSString *)channel
{
	[channelConnection writeData:[[NSString stringWithFormat:@"MSG %@:%@\n", channel, chat] dataUsingEncoding:NSUTF8StringEncoding]];
	[[NSNotificationCenter defaultCenter] postNotificationName:@"TUMSG" 
														object:self 
													  userInfo:[NSDictionary dictionaryWithObjectsAndKeys:login,@"sender", channel, @"channel", chat, @"message", NULL]];
}
@end
