/* Gridlock
Copyright (c) 2002-2003 by Brian Nenninger. All rights reserved.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

#import "ClientController.h"
#import "EDTCPSocket.h"
#import "Preferences.h"
#import "RendezvousUtils.h"

@implementation ClientController

idAccessor(socket, setSocket)
idAccessor(netConnection, setNetConnection)
idAccessor(rendezvousBrowser, setRendezvousBrowser)

-(id)init {
  [super init];
  [[NSNotificationCenter defaultCenter] addObserver:self
                                           selector:@selector(readPropertyList:)
                                               name:@"NetConnectionReadPropertyListNotification"
                                             object:nil];
  [[NSNotificationCenter defaultCenter] addObserver:self
                                           selector:@selector(gotNetworkConnection:)
                                               name:@"NetConnectionEstablishedNotification"
                                             object:nil];
  [[NSNotificationCenter defaultCenter] addObserver:self
                                           selector:@selector(networkConnectionTerminated:)
                                               name:@"NetConnectionTerminatedNotification"
                                             object:nil];
  rendezvousServers = [[NSMutableArray alloc] init];
  return self;
}

-(void)dealloc {
  [[NSNotificationCenter defaultCenter] removeObserver:self];
  [self setSocket:nil];
  [self setNetConnection:nil];
  [rendezvousServers release];

  [super dealloc];
}

idAccessor(gameConfiguration, setGameConfiguration)

-(void)awakeFromNib {
  isWindowExpanded = YES;
  windowHeightDelta = [windowSizerField frame].origin.y * [window userSpaceScaleFactor_];
  [self setUseRendezvousServer:NO];
  [self setRendezvousEnabled:NO];
  [rendezvousHostsPopup removeAllItems];

  // kick off rendezvous discovery...
  [self setupRendezvousDiscovery];

  [connectionStatusField setStringValue:@"Not connected"];
  [usernameField setStringValue:[[Preferences sharedInstance] networkUsername]];
  
  [self showWindow];
}

-(void)showWindow {
  [self setWindowExpanded:NO display:NO];
  [connectionStatusField setStringValue:@""];
  [windowSizerField setStringValue:@""];
  [window makeKeyAndOrderFront:nil];
}

-(void)setupRendezvousDiscovery {
  if (isRendezvousAvailable_()) {
    id browser = [[[nsNetServiceBrowserClass_() alloc] init] autorelease];
    [self setRendezvousBrowser:browser];
    [browser setDelegate:self];
    [browser searchForServicesOfType:@"_gridlock._tcp" inDomain:@""];
  }
}

-(void)setUseRendezvousServer:(BOOL)value {
  [rendezvousCheckbox setState:(value) ? NSOnState : NSOffState];
  [hostnameCheckbox setState:(!value) ? NSOnState : NSOffState];
}
-(BOOL)useRendezvousServer {
  return [rendezvousCheckbox state]==NSOnState;
}

-(void)setRendezvousEnabled:(BOOL)value {
  [rendezvousCheckbox setEnabled:value];
  [rendezvousHostsPopup setEnabled:value];
  if (!value) {
    [self setUseRendezvousServer:NO];
  }
}

-(void)setWindowExpanded:(BOOL)isExp display:(BOOL)disp {
  if (isExp && !isWindowExpanded) {
    // expand
    NSRect frame = [window frame];
    [window setFrame:NSMakeRect(frame.origin.x, frame.origin.y-windowHeightDelta,
                                frame.size.width, frame.size.height+windowHeightDelta)
             display:disp
             animate:YES];
  }
  else if (!isExp && isWindowExpanded) {
    // collapse
    NSRect frame = [window frame];
    [window setFrame:NSMakeRect(frame.origin.x, frame.origin.y+windowHeightDelta,
                                frame.size.width, frame.size.height-windowHeightDelta)
             display:disp
             animate:YES];
  }
  isWindowExpanded = isExp;
}

-(BOOL)hasExistingConnection {
  // not very nice...
  return ([[[[[NSApp delegate] gameController] gameState] allNetConnections] count]>0);
}

-(int)nextConnectionID {
  return ++connectionIDCounter;
}

-(NSFileHandle *)connectToHostname:(NSString *)hostname port:(int)port {
  EDTCPSocket *sock = [EDTCPSocket socket];
  NS_DURING
    [sock connectToHost:[NSHost hostWithName:hostname] port:port];
    NSLog(@"Got connection");
  NS_HANDLER
    sock = nil;
  NS_ENDHANDLER
  return sock;
}

-(void)connectInNewThread:(NSDictionary *)dict {
  NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
  NSMutableDictionary *resultDict = [NSMutableDictionary dictionary];
  NSFileHandle *sock = [self connectToHostname:[dict objectForKey:@"hostname"]
                                          port:[[dict objectForKey:@"port"] intValue]];

  [resultDict setObject:[dict objectForKey:@"connectionID"] forKey:@"connectionID"];
  if (sock) [resultDict setObject:sock forKey:@"socket"];
  
  [self performSelectorOnMainThread:@selector(connectionCallback:)
                         withObject:resultDict
                      waitUntilDone:YES];
   
  [pool release];
}

-(void)connectionCallback:(NSDictionary *)resultDict {
  // ignore if we weren't waiting for this connection or if we already have one
  if ([[resultDict objectForKey:@"connectionID"] intValue]!=waitingForConnectionID) return;
  if ([self hasExistingConnection]) return;
  
  if ([resultDict objectForKey:@"socket"]) {
    [self setSocket:[resultDict objectForKey:@"socket"]];
    [self setNetConnection:[NetConnection connectionWithSocket:[self socket]]];
    [self sendConnectMessage];
  }
  else {
    [self setSocket:nil];
    [self setNetConnection:nil];
    [connectionStatusField setStringValue:@"Unable to connect"];
  }
}

-(void)cancelConnect:(id)sender {
  if (waitingForConnectionID>0) {
    waitingForConnectionID = 0;
    [connectionStatusField setStringValue:@"Connect cancelled"];
  }
}

- (IBAction)connect:(id)sender {
  NSString *hostname = nil;
  int port = 0;

  [self updateUsername:nil];
  
  if ([self hasExistingConnection]) {
    [connectionStatusField setStringValue:@"Already connected"];
    return;
  }
  
  if ([rendezvousCheckbox state]==NSOnState) {
    id rendezvousService = [[rendezvousHostsPopup selectedItem] representedObject];
    getHostAndPortForNetService_(rendezvousService, &hostname, &port);
    NSLog(@"Using server info from Rendezvous: %@:%d", hostname, port);
  }
  else {
    hostname = [hostField stringValue];
    port = [portField intValue];
  }

  if ([hostname length] && port) {
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:hostname forKey:@"hostname"];
    [dict setObject:[NSNumber numberWithInt:port] forKey:@"port"];
    [dict setObject:[NSNumber numberWithInt:(waitingForConnectionID=[self nextConnectionID])] forKey:@"connectionID"];

    [connectionStatusField setStringValue:@"Connecting..."];
    [NSThread detachNewThreadSelector:@selector(connectInNewThread:) toTarget:self withObject:dict];
  }

}

- (IBAction)connectMethodChanged:(id)sender {
  if (sender==rendezvousCheckbox) {
    [hostnameCheckbox setState:NSOffState];
  }
  else {
    [rendezvousCheckbox setState:NSOffState];
  }
}

- (IBAction)disconnect:(id)sender {
  [[self socket] closeFile];
  [self setSocket:nil];
  [self setNetConnection:nil];
  [connectionStatusField setStringValue:@"Not connected"];
  //[self setWindowExpanded:NO display:YES];
}

- (IBAction)rendezvousHostSelected:(id)sender
{
}

-(void)sendConnectMessage {
  NSMutableDictionary *dict = [NSMutableDictionary dictionary];
  [dict setObject:@"" forKey:@"connect"];
  if ([passwordField stringValue]) [dict setObject:[passwordField stringValue] forKey:@"password"];
  [dict setObject:[[Preferences sharedInstance] networkUsername] forKey:@"username"];
  [netConnection transmitPropertyList:dict];
}

- (IBAction)startGame:(id)sender {
  NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
    [self gameConfiguration], @"configuration",
    [self netConnection], @"connection",
    [NSNumber numberWithInt:1], @"playerNumber",
    nil];
  [[NSNotificationCenter defaultCenter] postNotificationName:@"NetConnectionEstablishedNotification"
                                                      object:self userInfo:dict];
}


-(void)readPropertyList:(NSNotification *)notification {
  if ([self netConnection]==[notification object]) {
    id plist = [[notification userInfo] objectForKey:@"plist"];
    if ([plist objectForKey:@"start"]) {
      id configPlist = [plist objectForKey:@"configuration"];
      NSString *username = [plist objectForKey:@"username"];
      
      [[self netConnection] setRemoteUsername:username];
      [self setGameConfiguration:[[[GameConfiguration alloc] initFromPropertyList:configPlist] autorelease]];
      if ([self gameConfiguration]) {
        [self startGame:nil];
      }
      else {
        [self disconnect:nil];
        [connectionStatusField setStringValue:@"Connection Error"];        
      }
    }
    else if ([plist objectForKey:@"refused"]) {
      [self setSocket:nil];
      [connectionStatusField setStringValue:@"Connection refused"];
      //[self setWindowExpanded:NO display:YES];
    }
  }
}

-(IBAction)updateUsername:(id)sender {
  [[Preferences sharedInstance] setNetworkUsername:[usernameField stringValue]];
}

// called when a connection is established (could be from connecting by this window or from server)
-(void)gotNetworkConnection:(NSNotification *)notification {
  [self setSocket:nil];
  [self setNetConnection:nil];
  [window orderOut:nil];
  waitingForConnectionID = 0;
}

-(void)networkConnectionTerminated:(NSNotification *)notification {

}

-(void)windowWillClose:(NSNotification *)notification {
  if (window==[notification object]) {
    [self cancelConnect:nil];
  }
}

// Rendezvous delegate methods
-(void)netServiceBrowserWillSearch:(id)browser {
}

-(void)netServiceBrowser:(id)browser didFindService:(id)service moreComing:(BOOL)moreComing {
  [service setDelegate:self];
  [service resolve];
  if (!moreComing) {
  }
}

-(void)netServiceBrowser:(id)browser didRemoveService:(id)service moreComing:(BOOL)moreComing {
  int index = [rendezvousHostsPopup indexOfItemWithRepresentedObject:service];
  [rendezvousServers removeObject:service];
  if (index>=0) [rendezvousHostsPopup removeItemAtIndex:index];
  if ([rendezvousHostsPopup numberOfItems]==0) {
    [self setRendezvousEnabled:NO];
  }
}

-(void)netServiceBrowserDidStopSearch:(id)browser {

}

-(NSString *)displayNameForNetServiceName:(NSString *)serviceName {
  // the name should have 4 fields separated by ':'
  NSArray *fields = [serviceName componentsSeparatedByString:@":"];
  if ([fields count]<4) return nil;
  else {
    NSString *game = [fields objectAtIndex:0];
    NSString *variation = [fields objectAtIndex:1];
    NSString *username = [fields objectAtIndex:2];
    NSString *rendezvousID = [fields objectAtIndex:3];
    if ([game length]==0 || [username length]==0 || [rendezvousID length]==0) return nil;
    // if rendezvousID is the same as ours, it's our own server and we don't want to show it
    if ([rendezvousID isEqual:rendezvousIdentifier_()]) return nil;
    if ([variation length]>0) {
      return [NSString stringWithFormat:@"%@ (%@) - %@", game, variation, username];
    }
    else {
      return [NSString stringWithFormat:@"%@ - %@", game, username];
    }
  }
}

-(void)netServiceDidResolveAddress:(id)service {
  NSString *displayName = [self displayNameForNetServiceName:[service name]];
  NSString *ipaddr = nil;
  int port = 0;
  getHostAndPortForNetService_(service, &ipaddr, &port);
  NSLog(@"Resolved service address:%@ port:%d", ipaddr, port);
  if (displayName) {
    [rendezvousServers addObject:service];
    [rendezvousHostsPopup addItemWithTitle:displayName];
    [[rendezvousHostsPopup lastItem] setRepresentedObject:service];
    [self setRendezvousEnabled:YES];
  }
}


@end
