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

@implementation GridlockGameState

-(id)init {
  [super init];
  aiPlayers = [[NSMutableDictionary alloc] init];
  networkPlayers = [[NSMutableDictionary alloc] init];
  return self;
}

-(void)dealloc {
  [aiPlayers release];
  aiPlayers = nil;
  [networkPlayers release];
  networkPlayers = nil;
  
  [super dealloc];
}

-(NSArray *)aiNamesForCurrentGame:(BOOL)firstTime requireHuman:(BOOL)requireHuman {
  NSString *gameName = [[self gameConfiguration] gameName];
  // read AI types from preferences
  NSString *player1AIType = [[Preferences sharedInstance] aiTypeForGame:gameName player:1];
  NSString *player2AIType = [[Preferences sharedInstance] aiTypeForGame:gameName player:2];

  if (firstTime) {
    // if both unset, we will default to the first AI type available for player 2
    NSArray *aiTypes = [[self gameConfiguration] allAINames];
    if (player1AIType==nil && player2AIType==nil && [aiTypes count]>0) {
      player2AIType = [aiTypes objectAtIndex:0];
    }
  }
  if (firstTime || requireHuman) {
    // if both set, revert player 1 to human (so we don't start out computer vs computer)
    if ([player1AIType length]>0 && [player2AIType length]>0) {
      player1AIType = @"";
    }
  }

  if (!player1AIType) player1AIType = @"";
  if (!player2AIType) player2AIType = @"";

  return [NSArray arrayWithObjects:player1AIType, player2AIType, nil];
}

// called when game is switched to update AIs from NSUserDefaults
-(void)updateAIsForNewGame:(BOOL)firstTime requireHuman:(BOOL)requireHuman {
  NSArray *aiNames = [self aiNamesForCurrentGame:firstTime requireHuman:requireHuman];
  int i;
  for(i=0; i<[aiNames count]; i++) {
    [self setAIName:[aiNames objectAtIndex:i] forPlayer:i+1];
  }
}

-(GameHistory *)gameHistory {
  return gameHistory;
}
-(void)setGameHistory:(GameHistory *)newHistory {
  if (newHistory!=gameHistory) {
    BOOL isSameGame = [[[newHistory gameConfiguration] gameName] isEqual:[[gameHistory gameConfiguration] gameName]];
    id temp = gameHistory;
    gameHistory = [newHistory retain];

    // twiddle the AIs for the first game (if we're not playing a network game)
    if (![self hasNetConnections]) [self updateAIsForNewGame:(temp==nil)
                                                requireHuman:!isSameGame];
    [temp release];
  }
}

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

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

-(BOOL)isPlayerHuman:(int)pnum {
  id key = [NSNumber numberWithInt:pnum];
  return (nil==[aiPlayers objectForKey:key] && nil==[networkPlayers objectForKey:key]);
}
-(BOOL)isCurrentPlayerHuman {
  return [self isPlayerHuman:[self currentPlayerNumber]];
}

-(NSArray *)availableAINames {
  return [[self gameConfiguration] allAINames];
}
-(NSArray *)availableAIDisplayNames {
  return [[self gameConfiguration] allAIDisplayNames];
}

-(NSString *)aiNameForPlayer:(int)pnum {
  NSString *name = [[aiPlayers objectForKey:[NSNumber numberWithInt:pnum]] name];
  return (name ? name : @"");
}

-(void)setAIName:(NSString *)aiName forPlayer:(int)pnum {
  id key = [NSNumber numberWithInt:pnum];
  [aiPlayers removeObjectForKey:key];
  [networkPlayers removeObjectForKey:key];
  if ([aiName length]>0) {
    GenericAI *ai = [[self gameConfiguration] aiWithName:aiName];
    if (ai) {
      [aiPlayers setObject:ai forKey:key];
    }
  }
  [[Preferences sharedInstance] setAIType:(aiName ? aiName : @"")
                                  forGame:[[self gameConfiguration] gameName]
                                   player:pnum];
  
}

-(void)makeAIMove {
  GenericAI *ai = [aiPlayers objectForKey:[NSNumber numberWithInt:[self currentPlayerNumber]]];
  // this move may be executing in a worker thread. If so, we need to protect the AI and game objects because they may be released
  // by the main thread, for example if the player is switched to human while the AI is still thinking.
  Game *game = [self currentGame];
  [[ai retain] autorelease];
  [[game retain] autorelease];
  [ai computeBestMoveForGame:game];
}

-(void)setNetConnection:(NetConnection *)conn forPlayer:(int)pnum {
  id key = [NSNumber numberWithInt:pnum];
  [aiPlayers removeObjectForKey:key];
  if (conn==nil) {
    [networkPlayers removeObjectForKey:key];
  }
  else {
    [networkPlayers setObject:conn forKey:key];
  }
}

-(void)makePlayerHuman:(int)pnum {
  [self setAIName:nil forPlayer:pnum];
  [self setNetConnection:nil forPlayer:pnum];
}

-(void)makeAllPlayersHuman {
  [aiPlayers removeAllObjects];
  [networkPlayers removeAllObjects];
}

-(int)playerNumberForNetConnection:(NetConnection *)conn {
  NSArray *keys = [networkPlayers allKeysForObject:conn];
  return ([keys count] ? [[keys lastObject] intValue] : 0);
}
-(NetConnection *)netConnectionForPlayer:(int)pnum {
  return [networkPlayers objectForKey:[NSNumber numberWithInt:pnum]];
}

-(BOOL)hasNetConnections {
  return [networkPlayers count]>0;
}
-(NSArray *)allNetConnections {
  return [networkPlayers allValues];
}

-(id)propertyList {
  NSMutableDictionary *plist = [NSMutableDictionary dictionary];
  [plist setObject:[[self gameHistory] propertyList] forKey:@"history"];
  {
    NSMutableDictionary *aiDict = [NSMutableDictionary dictionary];
    int i;
    for(i=1; i<=[[self currentGame] numberOfPlayers]; i++) {
      NSString *aiName = [self aiNameForPlayer:i];
      if ([aiName length]>0) {
        [aiDict setObject:aiName forKey:[[NSNumber numberWithInt:i] stringValue]];
      }
    }
    [plist setObject:aiDict forKey:@"AIs"];
  }
  return plist;
}

@end
