/* 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 "GameController.h"
#import "GenericAI.h"
#import "Preferences.h"
#import "NetConnection.h"

static NSString *SAVED_FRAME_NAME=@"WindowFrame";

@implementation GameController

-(id)init {
  if ((self=[super init])) {
    movePositions = [[NSMutableArray alloc] init];
    playerWins = [[NSMutableArray alloc] initWithObjects:[NSNumber numberWithInt:0],
                                                         [NSNumber numberWithInt:0],
                                                         [NSNumber numberWithInt:0], nil];
    [self setGameState:[[[GridlockGameState alloc] init] autorelease]];
  }
  return self;
}

-(void)dealloc {
  [[NSNotificationCenter defaultCenter] removeObserver:self];

  [self setGameState:nil];
  [movePositions release];
  [playerWins release];
  
  [super dealloc];
}

-(void)awakeFromNib {
  [self retain];
  
  // use Ataxx as default game if none set
  NSMutableDictionary *defaults = [NSMutableDictionary dictionary];
  [defaults setObject:@"Ataxx" forKey:@"initialGame"];
  [[NSUserDefaults standardUserDefaults] registerDefaults:defaults];
  
  // save difference between window width and height so resizing can maintain it
  widthDelta = [window frame].size.width - [window frame].size.height;

  // setting Autosave name in IB is not reliable
  [window setFrameUsingName:SAVED_FRAME_NAME];
  [window setFrameAutosaveName:SAVED_FRAME_NAME];

  if ([[NSUserDefaults standardUserDefaults] integerForKey:@"StatsVisible"]) {
    [self showStatisticsDrawer:nil];
  }

  [window setAcceptsMouseMovedEvents:YES];
  [self buildGamePopup];

  [player1TurnView setPlayerNumber:1];
  [player2TurnView setPlayerNumber:2];

  [[NSNotificationCenter defaultCenter] addObserver:self
                                           selector:@selector(gotNetworkConnection:)
                                               name:@"NetConnectionEstablishedNotification"
                                             object:nil];
  [[NSNotificationCenter defaultCenter] addObserver:self
                                           selector:@selector(networkConnectionTerminated:)
                                               name:@"NetConnectionTerminatedNotification"
                                             object:nil];
  [[NSNotificationCenter defaultCenter] addObserver:self
                                           selector:@selector(receivedPropertyListFromNetwork:)
                                               name:@"NetConnectionReadPropertyListNotification"
                                             object:nil];
  [[NSNotificationCenter defaultCenter] addObserver:self
                                           selector:@selector(aiComputedMoveInfo:)
                                               name:@"AIComputedBestMoveNotification"
                                             object:nil];

  [self updateNetworkStatus];
  
  // set the default game
  [self restartGameWithConfiguration:[GameConfiguration configurationFromDefaults]];

  // workaround for bug where drawer size can't be set in IB
  [networkDrawer setContentSize:NSMakeSize(481, 157)];
}

idAccessor(gameState, setGameState)

-(GameHistory *)gameHistory {
  return [[self gameState] gameHistory];
}
-(void)setGameHistory:(GameHistory *)value {
  [[self gameState] setGameHistory:value];
}

-(GameConfiguration *)gameConfiguration {
  return [[self gameHistory] gameConfiguration];
}

-(NSString *)gameName {
  return [[self gameConfiguration] gameName];
}
-(NSString *)gameDisplayName {
  return [[self gameConfiguration] gameDisplayName];
}

-(NSString *)gameVariationName {
  return [[self gameConfiguration] variationName];
}
-(NSString *)gameVariationDisplayName {
  return [[self gameConfiguration] variationDisplayName];
}

-(Game *)game {
  return [[self gameHistory] currentGame];
}

-(void)restartGameWithHistory:(GameHistory *)history {
  [self setGameHistory:history];

  [self cancelPendingAIMoves];
  [statusField setStringValue:@""];
  [[self gameConfiguration] saveToDefaults];

  [self buildPlayerPopups];
  [self buildConfigurationPopup];

  if (![[self game] showScores]) {
    [player1ScoreField setStringValue:@""];
    [player2ScoreField setStringValue:@""];
  }

  [boardView setDelegate:[[self gameConfiguration] viewDelegate]];
  [boardView setGameHistory:[self gameHistory]];

  [boardView setHighlightedPositions:nil];

  [gamePopup selectItemWithTitle:[self gameDisplayName]];
  [window setTitle:[self gameDisplayName]];

  [self updateNetworkStatus];

  [self gameStateChanged];  
}

-(void)restartGameWithConfiguration:(GameConfiguration *)gameConfig {
  [self restartGameWithHistory:[[[GameHistory alloc] initWithGameConfiguration:gameConfig] autorelease]];
}

-(void)restartGame {
  [self restartGameWithConfiguration:[self gameConfiguration]];
}

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

-(void)buildConfigurationPopup {
  NSArray *variationDisplayNames = [[self gameConfiguration] allVariationDisplayNames];
  NSArray *variationNames = [[self gameConfiguration] allVariationNames];
  if ([variationDisplayNames count]>1) {
    int i;
    
    [configurationPopup removeAllItems];
    [configurationPopup setEnabled:YES];
    for(i=0; i<[variationDisplayNames count]; i++) {
      [configurationPopup addItemWithTitle:[variationDisplayNames objectAtIndex:i]];
      [[configurationPopup lastItem] setRepresentedObject:[variationNames objectAtIndex:i]];
    }
    [configurationPopup selectItemWithTitle:[[self gameConfiguration] variationDisplayName]];
  }
  else {
    [configurationPopup removeAllItems];
    [configurationPopup addItemWithTitle:NSLocalizedString(@"NoVariationsTitle", nil)];
    [configurationPopup setEnabled:NO];
  }
}


-(void)gameStateChanged {
  [self clearMovePositions];
  [self updateScores];
  [boardView setHighlightedPositions:nil];
  [boardView setFlashingPositions:nil];
  [boardView setNeedsDisplay:YES];
  [self cancelPendingAIMoves];

  if ([[self game] isGameOver]) {
    [self doGameOver];
  }
  else {
    [statusField setStringValue:@""];
    if ([self shouldMakeAIMove]) {
      [self makeAIMove];
    }
    else {
      [passButton setEnabled:[[self game] isPassValid]];
    }
  }
  [moveRecordTable reloadData];
}


-(BOOL)hasStartedMove {
  return ([[self movePositions] count]>0);
}

-(NSArray *)movePositions {
  return movePositions;
}

-(void)appendMovePosition:(id)position {
  [movePositions addObject:position];
}

-(void)setMovePositions:(NSMutableArray *)positions {
  [movePositions autorelease];
  movePositions = [positions retain];
}

-(void)removeLastPositionFromMove {
  [movePositions removeLastObject];
}

-(void)clearMovePositions {
  [movePositions removeAllObjects];
}

-(void)updateScores {
  int pnum = [[self game] currentPlayerNumber];
  if ([[self game] showScores]) {
    [player1ScoreField setIntValue:[[self game] scoreForPlayer:1]];
    [player2ScoreField setIntValue:[[self game] scoreForPlayer:2]];
  }
  [player1TurnView setVisible:(pnum==1)];
  [player2TurnView setVisible:(pnum==2)];
}

-(void)doGameOver {
  int wpnum = [[self game] winningPlayer];
  if (wpnum==0) {
    NSString *msg = [[NSBundle mainBundle] localizedStringForKey:@"TieMessage"
                                                           value:@"Tie"
                                                           table:nil];
    [statusField setStringValue:msg];
  }
  else {
    NSString *msg = [[NSBundle mainBundle] localizedStringForKey:@"WinMessage"
                                                           value:@"Player %d wins"
                                                           table:nil];
    [statusField setStringValue:[NSString stringWithFormat:msg,wpnum]];
  }
  [boardView setFlashingPositions:[[self game] positionsOfWinningPieces]];
  [passButton setEnabled:NO];
  //NSLog(@"Game Over: %d %d", [game scoreForPlayer:1], [game scoreForPlayer:2]);
  [playerWins replaceObjectAtIndex:wpnum
              withObject:[NSNumber numberWithInt:1+[[playerWins objectAtIndex:wpnum] intValue]]];
    
  [p1Wins setIntValue:[[playerWins objectAtIndex:1] intValue]];
  [p2Wins setIntValue:[[playerWins objectAtIndex:2] intValue]];

  /*
  if (FASTPLAY) {
    NSLog(@"Total record: %@", [playerWins componentsJoinedByString:@","]);
    if ([playerAIs count]==[[self game] numberOfPlayers]) {
      [self restartGame];
    }
  }
     */
}

-(void)doMoveSequence:(NSArray *)positions {
  // notify network players if this move wasn't received from the network
  //NSLog(@"Current player=%d", [[self game] currentPlayerNumber]);
  if (nil==[[self gameState] netConnectionForPlayer:[[self game] currentPlayerNumber]]) {
    [self sendMoveToNetworkPlayers:positions];
  }
  
  [[self game] prepareMoveSequence:positions];
  inAnimation = YES;
  {
    NSArray *positionsNotAnimating = [[Preferences sharedInstance] animateCapturedPieces] ?
                                        positions : [[self game] positionsOfAllChangingCells];

    [boardView setHighlightedPositions:nil];
    [boardView beginMoveAnimationForPositions:[[self game] positionsOfAllChangingCells]
                 immediatelyChangingPositions:positionsNotAnimating
                               callbackObject:positions];
  }
}

-(BOOL)isWaitingForHumanMove {
  return (![[self game] isGameOver] && !inAnimation &&
          [[self gameState] isCurrentPlayerHuman]);
}


-(void)boardView:(BoardView *)view clickedAtPosition:(DCHypergridPosition *)position {
  if (boardView && boardView==view && [self isWaitingForHumanMove]) {
    int row = [position row];
    int col = [position column];
    if (row>=0 && row<[[self game] numberOfRows] && col>=0 && col<[[self game] numberOfColumns]) {
      id position = [DCHypergridPosition positionWithRow:row column:col];
      //NSLog(@"Got click at row:%d col:%d", row, col);

      [self appendMovePosition:position];
      if ([[self game] isCompleteMoveSequenceValid:[self movePositions]]) {
        // FIXME: if the sequence is also a valid partial move, we should require confirmation
        //NSLog(@"Executing move");
        [self doMoveSequence:[self movePositions]];
      }
      else if ([[self game] isPartialMoveSequenceValid:[self movePositions]]) {
        // do nothing, keep added position
        //NSLog(@"Added to move sequence");
      }
      else {
        // not a valid move, but check if it's a valid move or start by itself
        NSMutableArray *newArray = [NSMutableArray arrayWithObject:position];
        [self removeLastPositionFromMove];
        if ([[self game] isPartialMoveSequenceValid:newArray]) {
          //NSLog(@"Started new move");
          [self setMovePositions:newArray];
        }
        else {
          // we don't want to execute it if it's a complete move
          [self clearMovePositions];
        }
        [boardView setHighlightedPositions:[[[self movePositions] copy] autorelease]];
      }      
    }
  }
}

-(void)recordAndExecuteMove:(NSArray *)move {
  [[self gameHistory] recordAndExecuteMove:move];
}

-(NSArray *)humanPlayerNumbers {
  NSMutableArray *humanNumbers = [NSMutableArray array];
  int i;
  for(i=0; i<[[self game] numberOfPlayers]; i++) {
    if ([[self gameState] isPlayerHuman:i+1]) {
      [humanNumbers addObject:[NSNumber numberWithInt:i+1]];
    }
  }
  return humanNumbers;
}

-(void)undoMove:(id)sender {
  if ([[self gameHistory] undoMovesUntilPlayerNumberInArray:[self humanPlayerNumbers]]) {
    [self gameStateChanged];
  }
  else {
    NSBeep();
  }
}

-(void)redoMove:(id)sender {
  if ([[self gameHistory] redoMovesUntilPlayerNumberInArray:[self humanPlayerNumbers]]) {
    [self gameStateChanged];
  }
  else {
    NSBeep();
  }
}

-(BOOL)validateMenuItem:(NSMenuItem *)item {
  // don't allow undo/redo in network games, and make sure the game state is undo/redoable
  // GNUstep selectors can't be compared with ==
  NSString *selName = NSStringFromSelector([item action]);
  if ([@"undoMove:" isEqualToString:selName]) {
    if ([self isInNetworkGame]) return NO;
    return [[self gameHistory] canUndoMovesUntilPlayerNumberInArray:[self humanPlayerNumbers]];
  }
  if ([@"redoMove:" isEqualToString:selName]) {
    if ([self isInNetworkGame]) return NO;
    return [[self gameHistory] canRedoMovesUntilPlayerNumberInArray:[self humanPlayerNumbers]];
  }
  if ([@"openDocument:" isEqualToString:selName]) {
    if ([self isInNetworkGame]) return NO;
  }
  return YES;
}

-(void)boardView:(BoardView *)view finishedMoveAnimation:(id)callbackObject {
  // callback object is positions in the move
  NSArray *moveToExecute = callbackObject;
  [self recordAndExecuteMove:moveToExecute];
  inAnimation = NO;
  [self gameStateChanged];
}

-(void)boardView:(BoardView *)view mouseMovedOverPosition:(DCHypergridPosition *)position {
  //NSLog(@"Mouse moved at row:%d col:%d", [position row], [position column]);
  if ([self isWaitingForHumanMove]) {
    if (position) {
      NSArray *moves = [[self movePositions] arrayByAddingObject:position];
      if ([[self game] isCompleteMoveSequenceValid:moves] || [[self game] isPartialMoveSequenceValid:moves]) {
        [boardView setHighlightedPositions:moves];
      }
      else {
        [boardView setHighlightedPositions:[[[self movePositions] copy] autorelease]];
      }
    }
    else {
      // mouse moved outside board
      [boardView setHighlightedPositions:[[[self movePositions] copy] autorelease]];
    }
  }
}

-(BOOL)shouldMakeAIMove {
  if (0==[[[self gameState] aiNameForPlayer:[[self game] currentPlayerNumber]] length]) return NO;
  if ([[self game] isGameOver]) return NO;

  return YES;
}

-(void)cancelPendingAIMoves {
  /* create a unique move ID that we want the results for, so if multiple responses come back (which can happen if
  the user switches AIs while in mid-move, we only accept one of them.
  */
  aiMoveID = (aiMoveID+1)%(1<<14);  
}

-(id)idForPendingAIMove {
  return [NSNumber numberWithInt:aiMoveID];
}

-(void)makeAIMove {
  [self cancelPendingAIMoves];
  // We need a delay here, or else if the AI thread comes back really fast (as it will for low search levels),
  // the main event loop will never get a chance to process user input so menus and buttons won't respond.
  [self performSelector:@selector(detachAIThread) withObject:nil afterDelay:0.01 inModes:[NSArray arrayWithObjects:NSDefaultRunLoopMode, NSEventTrackingRunLoopMode, NSModalPanelRunLoopMode, nil]];
}

-(void)detachAIThread {
  [NSThread detachNewThreadSelector:@selector(makeAIMoveInThread:) toTarget:self withObject:[self idForPendingAIMove]];
}

-(void)makeAIMoveInThread:(id)moveIDForThread {
  id pool = [[NSAutoreleasePool alloc] init];
  [[[NSThread currentThread] threadDictionary] setObject:moveIDForThread forKey:@"moveID"];
  [[self gameState] makeAIMove];
  [pool release];  
}

-(void)aiComputedMoveInfoMainThread:(NSArray *)params {
  if ([self isWaitingForHumanMove]) {
    NSLog(@"Got move from AI but controller is human, ignoring move");
    return;
  }
  else {
    id threadMoveID = [params objectAtIndex:1];
    // we don't need a threadsafe accessor for moveID because it's only ever read and written from the main thread
    if (![threadMoveID isEqual:[self idForPendingAIMove]]) {
      NSLog(@"Got wrong move ID from worker thread (%@, expected %@), ignoring move", threadMoveID, [self idForPendingAIMove]);
      return;
    }
    else {
      NSNotification *notification = [params objectAtIndex:0];      
      //GenericAI *ai = [notification object];
      NSDictionary *moveInfo = [notification userInfo];
      //NSLog(@"Received best move:%@ in thread:%@", move, [NSThread currentThread]);
      NSArray *move = [moveInfo objectForKey:@"move"];
      int positionsEvaluated = [[moveInfo objectForKey:@"positionsEvaluated"] intValue];
      
      double moveTime = [[moveInfo objectForKey:@"time"] doubleValue];
      
      [self doMoveSequence:move];
      
      [aiNumMovesEvaluatedField setIntValue:positionsEvaluated];
      [aiTimeField setDoubleValue:moveTime];
      [aiMovesPerSecondField setIntValue:(int)(positionsEvaluated/moveTime)];
    }
  }
}

-(void)aiComputedMoveInfo:(NSNotification *)notification {
  [self performSelectorOnMainThread:@selector(aiComputedMoveInfoMainThread:) 
                         withObject:[NSArray arrayWithObjects:notification,[[[NSThread currentThread] threadDictionary] objectForKey:@"moveID"], nil]
                      waitUntilDone:NO];
}

-(void)buildPlayerPopups {
  NSArray *aiTypes = [[self gameState] availableAINames];
  NSArray *aiDisplayNames = [[self gameState] availableAIDisplayNames];
  NSArray *popups = [NSArray arrayWithObjects:player1TypePopup,player2TypePopup,nil];
  NSEnumerator *pe = [popups objectEnumerator];
  NSPopUpButton *popup;

  int pnum = 1;
  while ((popup=[pe nextObject])) {
    int i;
    // representedObjects of popup items are the non-localized names of the AIs ("" for human)
    [popup removeAllItems];
    [popup addItemWithTitle:[[NSBundle mainBundle] localizedStringForKey:@"HumanPlayer" value:@"Human" table:nil]];
    [[popup lastItem] setRepresentedObject:@""];
    for(i=0; i<[aiDisplayNames count]; i++) {
      [popup addItemWithTitle:[[[NSBundle mainBundle] localizedStringForKey:@"ComputerPlayerPrefix"
                                                                      value:@"Human"
                                                                      table:nil]
                                stringByAppendingString:[aiDisplayNames objectAtIndex:i]]];
      [[popup lastItem] setRepresentedObject:[aiTypes objectAtIndex:i]];
    }
    [popup selectItemWithRepresentedObject_:[[self gameState] aiNameForPlayer:pnum]];

    // check for network
    if (nil!=[[self gameState] netConnectionForPlayer:pnum]) {
      [popup addItemWithTitle:[[NSBundle mainBundle] localizedStringForKey:@"NetworkPlayer"
                                                                      value:@"Network"
                                                                      table:nil]];
      [popup selectItemAtIndex:[popup numberOfItems]-1];
    }
    // FIXME: hide menu if only item is "Human"
    ++pnum;
  }
}


-(BOOL)allowRestart {
  if ([[self game] isGameOver] || [[self game] moveCount]==0) {
    return YES;
  }
  else {
    // game is in progress, show confirmation dialog
    NSString *title = NSLocalizedString(@"RestartTitle", nil);
    NSString *okLabel = NSLocalizedString(@"RestartOK", nil);
    NSString *cancelLabel = NSLocalizedString(@"RestartCancel", nil);
    NSString *msgText = NSLocalizedString(@"RestartMessage", nil);

    int result = NSRunAlertPanel(title, msgText, okLabel, cancelLabel, nil);
    return (result==NSAlertDefaultReturn);
  }
}

-(BOOL)confirmNetworkDisconnect {
  NSString *title = NSLocalizedString(@"DisconnectTitle", nil);
  NSString *okLabel = NSLocalizedString(@"DisconnectOK", nil);
  NSString *cancelLabel = NSLocalizedString(@"DisconnectCancel", nil);
  NSString *msgText = NSLocalizedString(@"DisconnectMessage", nil);

  int result = NSRunAlertPanel(title, msgText, okLabel, cancelLabel, nil);
  return (result==NSAlertDefaultReturn);
}

-(IBAction)playerTypeUpdated:(id)sender {
  int pnum = [sender tag];
  NSString *aiName = [[sender selectedItem] representedObject];
  // if in network game, changing player type will disconnect
  if (![self isInNetworkGame] || [self confirmNetworkDisconnect]) {
    [self dropAllNetConnections];
    [[self gameState] setAIName:aiName forPlayer:pnum];
    if ([self shouldMakeAIMove]) {
      [self makeAIMove];
    }
  }
  [self buildPlayerPopups];
}

-(IBAction)configurationSelectedFromPopup:(id)sender {
  if ([self allowRestart]) {
    NSString *varname = [[sender selectedItem] representedObject];
    GameConfiguration *newConfig = [[[GameConfiguration alloc] initWithName:[self gameName] variation:varname] autorelease];
    [self restartGameWithConfiguration:newConfig];
    [self sendRestartToNetworkPlayers];
  }
  else {
    [sender selectItemWithTitle:[self gameVariationDisplayName]];
  }
}

-(IBAction)gameSelectedFromPopup:(id)sender {
  if ([self allowRestart]) {
    NSString *gameName = [[sender selectedItem] representedObject];
    GameConfiguration *newConfig = [[[GameConfiguration alloc] initWithName:gameName variation:nil] autorelease];
    [self restartGameWithConfiguration:newConfig];
    [self sendRestartToNetworkPlayers];
  }
  else {
    [sender selectItemWithTitle:[self gameName]];
  }
}

-(IBAction)passButtonClicked:(id)sender {
  if ([[self game] isCompleteMoveSequenceValid:nil]) {
    //NSLog(@"Executing move");
    [self doMoveSequence:nil];
  }
}

-(IBAction)restartGame:(id)sender {
  if ([self allowRestart]) {
    [[self gameConfiguration] createNewInitialGame];
    [self restartGame];
    [self sendRestartToNetworkPlayers];
  }
}

-(void)restartSheetEnded:(NSWindow *)window returnCode:(int)code contextInfo:(void *)unused {
  if (code==NSAlertDefaultReturn) {
    [self restartGame];
  }
}

-(void)windowWillClose:(NSNotification *)note {
  // clear any previous delayed invocations because they retain their targets
  [self cancelPendingAIMoves];
  [self autorelease];
  // terminate app
  [[NSApplication sharedApplication] performSelector:@selector(terminate:) withObject:nil afterDelay:0.01];
}

-(NSSize)windowWillResize:(NSWindow *)win toSize:(NSSize)newSize {
  if (newSize.width > newSize.height+widthDelta) {
    return NSMakeSize(newSize.height+widthDelta, newSize.height);
  }
  else {
    return NSMakeSize(newSize.width, newSize.width-widthDelta);
  }
}

// recorded move table view data source methods
-(int)numberOfRowsInTableView:(NSTableView *)table {
  return [[self gameHistory] numberOfMoves]/2;
}

-(id)tableView:(NSTableView *)table objectValueForTableColumn:(NSTableColumn *)tableColumn row:(int)row {
  int col = [[tableColumn identifier] intValue];
  int index = [[table tableColumns] count]*row + col - 1;
  NSArray *move = [[self gameHistory] moveWithNumber:index];
  return (move) ? [[self game] descriptionForMove:move] : @"";
}

-(void)tableView:(NSTableView *)table willDisplayCell:(id)cell forTableColumn:(NSTableColumn *)tableColumn row:(int)row {
  int col = [[tableColumn identifier] intValue];
  int index = [[table tableColumns] count]*row + col - 1;
  if (index>=[[self gameHistory] currentMoveNumber]) {
    [cell setTextColor:[NSColor redColor]];
  }
  else {
    [cell setTextColor:[NSColor blackColor]];
  }
}

-(BOOL)tableView:(NSTableView *)aTableView shouldEditTableColumn:(NSTableColumn *)aTableColumn row:(int)rowIndex {
  return NO;
}

//////////////////////////////////////////////////////////////////////////////////
// loading and saving games
-(id)propertyList {
  NSMutableDictionary *plist = [NSMutableDictionary dictionary];
  [plist setObject:[[self gameHistory] propertyList] forKey:@"history"];
  {
    NSMutableDictionary *aiDict = [NSMutableDictionary dictionary];
    int i;
    for(i=1; i<=[[self game] numberOfPlayers]; i++) {
      NSString *aiName = [[self gameState] aiNameForPlayer:i];
      if ([aiName length]>0) {
        [aiDict setObject:aiName forKey:[[NSNumber numberWithInt:i] stringValue]];
      }
    }
    [plist setObject:aiDict forKey:@"AIs"];
  }
  return plist;
}
-(void)updateFromPropertyList:(id)plist {
  GameHistory *newHistory = [[[GameHistory alloc] initFromPropertyList:[plist objectForKey:@"history"]] autorelease];
  if (newHistory) {
    // update AIs in Preferences, they will be created in restartGame...
    NSDictionary *aiDict = [plist objectForKey:@"AIs"];
    int i;
    for(i=1; i<=[[newHistory currentGame] numberOfPlayers]; i++) {
      NSString *aiName = [aiDict objectForKey:[NSString stringWithFormat:@"%d",i]];
      if (!aiName) aiName = @"";
      [[Preferences sharedInstance] setAIType:aiName forGame:[[newHistory gameConfiguration] gameName] player:i];
    }
    [self restartGameWithHistory:newHistory];
  }
  else {
    NSLog(@"Failed to load game");
  }
}

-(void)saveGameToURL:(NSURL *)url {
  id plist = [self propertyList];
  if ([plist writeToURL:url atomically:YES]==NO) {
    NSLog(@"Error saving game to:%@", url);
    [self performSelector:@selector(showSaveFailedPanelForURL:) withObject:url afterDelay:0.0];
  }
}

-(IBAction)saveDocument:(id)sender {
  NSSavePanel *panel = [NSSavePanel savePanel];
  // GNUstep doesn't like sheets (it implements the methods but the return code isn't set)
#ifdef GNUSTEP
  if ([panel runModal]==NSFileHandlingPanelOKButton) {
    [self saveGameToURL:[panel URL]];
  }
#else
  [panel beginSheetForDirectory:nil file:nil modalForWindow:window modalDelegate:self didEndSelector:@selector(savePanelEnded:returnCode:contextInfo:) contextInfo:nil];
#endif
}

-(void)showSaveFailedPanelForURL:(NSURL *)url {
  NSRunAlertPanel(NSLocalizedString(@"SaveFailedTitle", nil),
                  NSLocalizedString(@"SaveFailedMessage", nil), nil, nil, nil);
}

-(void)savePanelEnded:(NSSavePanel *)panel returnCode:(int)code contextInfo:(void *)info {
  if (code==NSOKButton) {
    [self saveGameToURL:[panel URL]];
  }
}

-(void)loadGameFromURL:(NSURL *)url {
  id plist;
NS_DURING
  plist = [[NSString stringWithContentsOfURL:url] propertyList];
NS_HANDLER
  plist = nil;
NS_ENDHANDLER
  if (plist) {
    [self updateFromPropertyList:plist];
  }
  else {
    NSLog(@"Can't restore saved game from:%@", url);
    [self performSelector:@selector(showLoadFailedPanelForURL:) withObject:url afterDelay:0.0];
  }
}

-(IBAction)openDocument:(id)sender {
  if ([self isInNetworkGame]) {
    NSBeep();
  }
  else {
    NSOpenPanel *panel = [NSOpenPanel openPanel];
    // GNUstep doesn't like sheets (it implements the methods but the return code isn't set)
#ifdef GNUSTEP
    if ([panel runModalForTypes:nil]==NSOKButton) {
      [self loadGameFromURL:[panel URL]];
    }
#else
    [panel beginSheetForDirectory:nil file:nil modalForWindow:window modalDelegate:self didEndSelector:@selector(openPanelEnded:returnCode:contextInfo:) contextInfo:nil];
#endif
  }
}

-(void)showLoadFailedPanelForURL:(NSURL *)url {
  NSRunAlertPanel(NSLocalizedString(@"LoadFailedTitle", nil),
                  NSLocalizedString(@"LoadFailedMessage", nil), nil, nil, nil);
}

-(void)openPanelEnded:(NSSavePanel *)panel returnCode:(int)code contextInfo:(void *)info {
  if (code==NSOKButton) {
    [self loadGameFromURL:[panel URL]];
  }
}


/////////////////////////////////////////////////////////////////////////////////////
// network support

-(BOOL)isInNetworkGame {
  return [[[self gameState] allNetConnections] count]>0;
}

-(void)gotNetworkConnection:(NSNotification *)notification {
  id playerNum = [[notification userInfo] objectForKey:@"playerNumber"];
  NetConnection *connection = [[notification userInfo] objectForKey:@"connection"];
  GameConfiguration *config = [[notification userInfo] objectForKey:@"configuration"];
  if (playerNum && connection && config) {
    NSLog(@"Got remote connection, restarting");
    [self restartGameWithConfiguration:config];
    // update player menus
    [[self gameState] makeAllPlayersHuman];
    [[self gameState] setNetConnection:connection forPlayer:[playerNum intValue]];
    [self buildPlayerPopups];

    [self updateNetworkStatus];
    
    [self showNetworkDrawer:nil];
  }
}

-(void)sendPropertyListToNetworkPlayers:(id)plist {
  [[[self gameState] allNetConnections] makeObjectsPerformSelector:@selector(transmitPropertyList:) withObject:plist];  
}

-(void)updateNetworkStatus {
  NSArray *connections = [[self gameState] allNetConnections];
  if ([connections count]>0) {
    // for now assume only one
    id conn = [connections objectAtIndex:0];
    [networkStatusField setStringValue:[NSString stringWithFormat:NSLocalizedString(@"NetworkStatusConnected", nil), [conn remoteIPAddress]]];
    [disconnectButton setEnabled:YES];
    [chatMessageField setEnabled:YES];
  }
  else {
    [networkStatusField setStringValue:NSLocalizedString(@"NetworkStatusNotConnected", nil)];
    [disconnectButton setEnabled:NO];
    [chatMessageField setEnabled:NO];
  }  
}

-(void)dropAllNetConnections {
  [[[self gameState] allNetConnections] makeObjectsPerformSelector:@selector(sendDisconnect)];
}

-(IBAction)disconnectButtonClicked:(id)sender {
  if ([self isInNetworkGame] && [self confirmNetworkDisconnect]) {
    [self dropAllNetConnections];
  }
}

-(void)dropNetConnectionForPlayer:(NSNumber *)pnum {
  [[[self gameState] netConnectionForPlayer:[pnum intValue]] setIsDisconnected:YES];
  [[self gameState] setNetConnection:nil forPlayer:[pnum intValue]];
  [self buildPlayerPopups];
  // this won't work if >2 players
  [self updateNetworkStatus];
}

-(void)receivedPropertyListFromNetwork:(NSNotification *)notification {
  int pnum = [[self gameState] playerNumberForNetConnection:[notification object]];
  if (pnum>0) {
    NSDictionary *plist = [[notification userInfo] objectForKey:@"plist"];
    //NSLog(@"Read plist from network:%@", [plist description]);
    // check for disconnect or error
    if ([plist objectForKey:@"disconnect"]) {
      NSLog(@"Received disconnect");
      // we want to keep the connection around until the next run loop, otherwise
      // there are timing problems where the NetConnection can get data notifications
      // just after it's dealloced.
      [self performSelector:@selector(dropNetConnectionForPlayer:) withObject:[NSNumber numberWithInt:pnum] afterDelay:0.0];
    }
    else if ([plist objectForKey:@"error"]) {
      NSLog(@"Received error:%@", [plist objectForKey:@"error"]);
      [self performSelector:@selector(dropNetConnectionForPlayer:) withObject:[NSNumber numberWithInt:pnum] afterDelay:0.0];
    }
    else if ([plist objectForKey:@"chat"]) {
      NSString *msg = [plist objectForKey:@"chat"];
      //NSLog(@"Received chat message:%@", msg);
      [chatTranscriptArea appendText:[NSString stringWithFormat:@"%@: %@\n",
                                               [[notification object] remoteUsername], msg]
                        scrollToEnd_:YES];
    }
    else if ([plist objectForKey:@"restart"]) {
      // TODO: ask for verification
      GameConfiguration *config = [self gameConfiguration];
      NSDictionary *configPlist = [plist objectForKey:@"configuration"];
      if (configPlist) {
        config = [[[GameConfiguration alloc] initFromPropertyList:configPlist] autorelease];
      }
      [self restartGameWithConfiguration:config];
      [chatTranscriptArea appendText:[NSLocalizedString(@"GameRestartedMessage",nil) stringByAppendingString:@"\n"] scrollToEnd_:YES];
    }
    else if ([plist objectForKey:@"start"]) {
      // do nothing, this is the start request, handled in ClientController
    }
    else {
      NSArray *moveStrings = [plist objectForKey:@"move"];
      id gamePlist = [plist objectForKey:@"game"];
      //NSLog(@"Got move from network:%@", [moveStrings description]);
      if (moveStrings && gamePlist) {
        // make sure it's the right turn
        if (pnum!=[[self game] currentPlayerNumber]) {
          NSLog(@"Move for player %d received when player %d's turn", pnum, [[self game] currentPlayerNumber]);
          [self performSelector:@selector(dropNetConnectionForPlayer:) withObject:[NSNumber numberWithInt:pnum] afterDelay:0.0];
        }
        else {
          // validate move
          NSArray *move = [DCHypergridPosition positionArrayFromPropertyListValueArray:moveStrings];
          Game *gameCopy = [[[self game] copy] autorelease];
          if ([gameCopy isCompleteMoveSequenceValid:move] && [gameCopy makeMoveSequence:move]) {
            // move is valid, make sure the resulting state matches
            Game *gameFromClient = [[[[self gameConfiguration] initialGame] copy] autorelease];
            [gameFromClient updateFromPropertyList:gamePlist];
            if ([[gameCopy grid] isEqualToHypergrid:[gameFromClient grid]]) {
              // good move, execute
              [self doMoveSequence:move];
            }
            else {
              NSLog(@"Inconsistency in game state from client");
              [self performSelector:@selector(dropNetConnectionForPlayer:) withObject:[NSNumber numberWithInt:pnum] afterDelay:0.0];
            }
          }
          else {
            NSLog(@"Received invalid move from client:%@", [move description]);
            [self performSelector:@selector(dropNetConnectionForPlayer:) withObject:[NSNumber numberWithInt:pnum] afterDelay:0.0];
          }
        }
      }
      else {
        NSLog(@"Received unrecognized message:%@", [plist description]);
      }
    }
  }
}

-(IBAction)sendChatMessage:(id)sender {
  if ([[chatMessageField stringValue] length]>0 && [[[self gameState] allNetConnections] count]>0) {
    NSMutableDictionary *chatDict = [NSMutableDictionary dictionary];
    [chatDict setObject:[chatMessageField stringValue] forKey:@"chat"];
    [self sendPropertyListToNetworkPlayers:chatDict];
    [chatTranscriptArea appendText:[NSString stringWithFormat:@"%@: %@\n", [[Preferences sharedInstance] networkUsername], [chatMessageField stringValue]] scrollToEnd_:YES];
  }
  [chatMessageField setStringValue:@""];
}

-(void)sendMoveToNetworkPlayers:(NSArray *)move {
  if ([[self gameState] hasNetConnections]) {
    Game *gameCopy = [[[self game] copy] autorelease];
    NSMutableDictionary *movePlist = [NSMutableDictionary dictionary];
    NSEnumerator *ne = [[[self gameState] allNetConnections] objectEnumerator];
    id conn;
    
    [gameCopy makeMoveSequence:move];
    [movePlist setObject:[move valuesByObjectsPerformingSelector:@selector(propertyListValue)] forKey:@"move"];
    //NSLog(@"move array:%@", move);
    [movePlist setObject:[gameCopy propertyList] forKey:@"game"];

    while ((conn=[ne nextObject])) {
      //NSLog(@"Writing plist to network:%@", [movePlist description]);
      [conn transmitPropertyList:movePlist];
    }
  }
}

-(void)sendRestartToNetworkPlayers {
  NSMutableDictionary *restartDict = [NSMutableDictionary dictionary];
  [restartDict setObject:@"1" forKey:@"restart"];
  [restartDict setObject:[[self gameConfiguration] propertyList] forKey:@"configuration"];
  [self sendPropertyListToNetworkPlayers:restartDict];
}

-(void)networkConnectionTerminated:(NSNotification *)notification {
  int pnum = [[self gameState] playerNumberForNetConnection:[notification object]];
  if (pnum>0) {
    [self dropNetConnectionForPlayer:[NSNumber numberWithInt:pnum]];
  }
}


/////////////////////////////////////////////////////////////////////////////////

/* These methods operate on both the drawer and window ivars. One of each will be nil
(window ivar is not set in OS X, drawer is not set in GNUstep), messages to them will be ignored.
*/
-(IBAction)toggleStatisticsDrawer:(id)sender {
  [statisticsDrawer toggle:self];
  [statisticsWindow makeKeyAndOrderFront:nil];
}
-(IBAction)showStatisticsDrawer:(id)sender {
  [(NSDrawer *)statisticsDrawer open];
  [statisticsWindow makeKeyAndOrderFront:nil];
}

-(IBAction)toggleNetworkDrawer:(id)sender {
  [networkDrawer toggle:self];
  [networkWindow makeKeyAndOrderFront:nil];
}
-(IBAction)showNetworkDrawer:(id)sender {
  [(NSDrawer *)networkDrawer open];
  [networkWindow makeKeyAndOrderFront:nil];
}

-(void)drawerDidOpen:(NSNotification *)notification {
  if ([notification object]==statisticsDrawer) {
    [[NSUserDefaults standardUserDefaults] setInteger:1 forKey:@"StatsVisible"];
  }
}
-(void)drawerDidClose:(NSNotification *)notification {
  if ([notification object]==statisticsDrawer) {
    [[NSUserDefaults standardUserDefaults] setInteger:0 forKey:@"StatsVisible"];
  }
}

@end
