/* 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 "ServerController.h"
#import "EDTCPSocket.h"
#import "GameController.h"
#import "NetConnection.h"
#import "CocoaAdditions.h"
#import "Preferences.h"
#import "RendezvousUtils.h"

@implementation ServerController

idAccessor(netConnection, setNetConnection)
idAccessor(rendezvousService, setRendezvousService)

-(id)init {
  [super init];
  [[NSNotificationCenter defaultCenter] addObserver:self
                                           selector:@selector(connectionAccepted:)
                                               name:NSFileHandleConnectionAcceptedNotification
                                             object:nil];
  [[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];
  return self;
}

-(void)dealloc {
  [[NSNotificationCenter defaultCenter] removeObserver:self];
  [self setNetConnection:nil];
  
  [super dealloc];
}

-(void)awakeFromNib {
  isWindowExpanded = YES;
  windowHeightDelta = [windowSizerField frame].origin.y * [window userSpaceScaleFactor_];

  [connectionStatusField setStringValue:@"Not listening"];
  [self buildGamePopup];
  [usernameField setStringValue:[[Preferences sharedInstance] networkUsername]];
  [self gameSelectedFromPopup:nil];
  [self showWindow];
}

-(void)buildGamePopup {
  NSArray *displayNames = [GameConfiguration allGameDisplayNames];
  NSArray *names = [GameConfiguration allGameNames];
  [gamePopup setItemTitles:displayNames representedObjects_:names];
  [gamePopup selectItemAtIndex:0];
}

idAccessor(gameConfiguration, setGameConfiguration)

-(IBAction)gameSelectedFromPopup:(id)sender {
  NSString *gameName = [[gamePopup selectedItem] representedObject];
  GameConfiguration *newConfig = [[[GameConfiguration alloc] initWithName:gameName variation:nil] autorelease];
  NSArray *varDisplayNames = [newConfig allVariationDisplayNames];
  if ([varDisplayNames count]>1) {
    [variationPopup setItemTitles:varDisplayNames representedObjects_:[newConfig allVariationNames]];
    [variationPopup setEnabled:YES];
  }
  else {
    [variationPopup removeAllItems];
    [variationPopup addItemWithTitle:NSLocalizedString(@"NoVariationsTitle", nil)];
    [variationPopup setEnabled:NO];
  }
}

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

-(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;
}

-(NSFileHandle *)serverSocket {
  return serverSocket;
}
-(void)setServerSocket:(NSFileHandle *)fh {
  if (serverSocket!=fh) {
    id oldsocket = serverSocket;
    serverSocket = [fh retain];
    [oldsocket closeFile];
    [oldsocket release];

    [serverSocket acceptConnectionInBackgroundAndNotify];
  }
}

-(NSString *)rendezvousServiceName {
  NSMutableArray *fields = [NSMutableArray array];
  int i;
  [fields addObject:([gamePopup titleOfSelectedItem]) ? [gamePopup titleOfSelectedItem] : @""];
  [fields addObject:([variationPopup isEnabled]) ? [variationPopup titleOfSelectedItem] : @""];
  [fields addObject:[[Preferences sharedInstance] networkUsername]];
  [fields addObject:rendezvousIdentifier_()];
  // replace any colons with dashes, join by colons
  for(i=0; i<[fields count]; i++) {
    id newValue = [[[fields objectAtIndex:i] componentsSeparatedByString:@":"] componentsJoinedByString:@"-"];
    [fields replaceObjectAtIndex:i withObject:newValue];
  }
  return [fields componentsJoinedByString:@":"];
}

-(BOOL)publishRendezvousServiceOnPort:(int)port {
  if (isRendezvousAvailable_()) {
    id service = [[[nsNetServiceClass_() alloc] initWithDomain:@""
                                                          type:@"_gridlock._tcp"
                                                          name:[self rendezvousServiceName]
                                                          port:port] autorelease];
    [self setRendezvousService:service];
    [service setDelegate:self];
    [service publish];
    return YES;
  }
  return NO;
}

- (IBAction)beginHosting:(id)sender {
  int port = 0;
  [self updateUsername:nil];
  if ([self serverSocket]) return;

  NS_DURING
    EDTCPSocket *sock = [EDTCPSocket socket];
    port = [portField intValue];
    [sock startListeningOnLocalPort:port];
    [self setServerSocket:sock];
    [self publishRendezvousServiceOnPort:port];
  NS_HANDLER
    [self setServerSocket:nil];
    [connectionStatusField setStringValue:[NSString stringWithFormat:@"Unable to listen on port %d",port]];
  NS_ENDHANDLER

  if ([self serverSocket]) {
    [connectionStatusField setStringValue:[NSString stringWithFormat:@"Listening on port %d",port]];
  }
}

-(void)connectionAccepted:(NSNotification *)notification {
  if ([self serverSocket]==[notification object]) {
    NSFileHandle *clientSocket = [[notification userInfo] objectForKey:NSFileHandleNotificationFileHandleItem];
    if (clientSocket) {
      //[connectionStatusField setStringValue:@"Got connection"];
      //[self setWindowExpanded:YES display:YES];
      [self setNetConnection:[NetConnection connectionWithSocket:clientSocket]];
      // wait for connect request from client
    }
  }
}

- (IBAction)abortHosting:(id)sender {
  [self setServerSocket:nil];
  [self setNetConnection:nil];
  [[self rendezvousService] stop];
  [connectionStatusField setStringValue:@"Not listening"];
  //[self setWindowExpanded:NO display:NO];
}

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

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

  [self abortHosting:nil];
  [window orderOut:nil];
}

-(void)readPropertyList:(NSNotification *)notification {
  if ([self netConnection]==[notification object]) {
    id plist = [[notification userInfo] objectForKey:@"plist"];
    if ([plist objectForKey:@"connect"]) {
      NSString *username = [plist objectForKey:@"username"];
      NSString *password = [plist objectForKey:@"password"];
      NSString *requiredPassword = [passwordField stringValue];

      if (([password length]==0 && [requiredPassword length]==0) || [password isEqual:requiredPassword]) {
        GameConfiguration *config = [[[GameConfiguration alloc] initWithName:[[gamePopup selectedItem] representedObject] variation:[[variationPopup selectedItem] representedObject]] autorelease];
        NSMutableDictionary *startDict = [NSMutableDictionary dictionary];
        
        [[self netConnection] setRemoteUsername:username];
        [self setGameConfiguration:config];

        [startDict setObject:@"" forKey:@"start"];
        [startDict setObject:[[self gameConfiguration] propertyList] forKey:@"configuration"];
        [startDict setObject:[[Preferences sharedInstance] networkUsername] forKey:@"username"];
        [[self netConnection] transmitPropertyList:startDict];
        // todo: require confirmation from both players before starting
        // stop listening
        [self setServerSocket:nil];
        
        [self startGame:nil];
      }
      else {
        // bad password
        // because of complex object graph interactions, we need to delay sending the failure message
        // and disconnecting until the next cycle of the run loop
        [self performSelector:@selector(handleFailedConnect) withObject:nil afterDelay:0.0];
      }
    }
  }    
}

-(void)handleFailedConnect {
  NSMutableDictionary *failDict = [NSMutableDictionary dictionary];
  [failDict setObject:@"" forKey:@"refused"];
  [[self netConnection] transmitPropertyList:failDict];
  [self setNetConnection:nil];
  [[self serverSocket] acceptConnectionInBackgroundAndNotify];  
}

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

// called when connection is terminated (probably due to invalid input)
-(void)networkConnectionTerminated:(NSNotification *)notification {
  if ([notification object]==[self netConnection]) {
    [self setNetConnection:nil];
    [[self serverSocket] acceptConnectionInBackgroundAndNotify];
  }
}

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



// Rendezvous delegate methods
-(void)netServiceWillPublish:(id)service {
  NSLog(@"Rendezvous service published");
}

-(void)netService:(id)service didNotPublish:(NSDictionary *)errorDict {
  
}

-(void)netServiceDidStop:(id)service {
  NSLog(@"Rendezvous service stopped");
}

@end
