/* 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 "AutoplayController.h"
#import "GameConfiguration.h"
#import "GameHistory.h"

@implementation AutoplayController

-(id)init {
  if (self=[super init]) {
    moveStatistics = [[NSMutableDictionary alloc] init];
    playerWins = [[NSMutableDictionary alloc] init];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(aiComputedMoveInfo:)
                                                 name:@"AIComputedBestMoveNotification"
                                               object:nil];
  }
  return self;
}

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

  [super dealloc];
}

idAccessor(gameState, setGameState)

-(GridlockGameState *)createGameState {
  NSString *gameName = [[NSUserDefaults standardUserDefaults] objectForKey:@"AutoplayGame"];
  NSString *variationName = [[NSUserDefaults standardUserDefaults] objectForKey:@"AutoplayVariation"];
  GameConfiguration *config = [[[GameConfiguration alloc] initWithName:gameName variation:variationName] autorelease];
  GameHistory *history = [[[GameHistory alloc] initWithGameConfiguration:config] autorelease];

  GridlockGameState *state = [[[GridlockGameState alloc] init] autorelease];
  [state setGameHistory:history];
  [state setAIName:[[NSUserDefaults standardUserDefaults] objectForKey:@"AutoplayAI1"] forPlayer:1];
  [state setAIName:[[NSUserDefaults standardUserDefaults] objectForKey:@"AutoplayAI2"] forPlayer:2];
  
  return state;
}

-(void)incrementWinsForPlayer:(int)pnum {
  id key = [NSNumber numberWithInt:pnum];
  int prevWins = [[playerWins objectForKey:key] intValue];
  [playerWins setObject:[NSNumber numberWithInt:prevWins+1] forKey:key];
}

// compute the average moves per second, which is not the total moves divided by total time
-(void)recordStatistics:(NSDictionary *)statsDict forPlayer:(int)pnum {
  id key = [NSNumber numberWithInt:pnum];
  int numMoves = [[statsDict objectForKey:@"positionsEvaluated"] intValue];
  double moveTime = [[statsDict objectForKey:@"time"] doubleValue];
  double movesPerSecond = ((double)numMoves)/moveTime;
  
  NSMutableDictionary *playerStats = [moveStatistics objectForKey:key];
  if (!playerStats) {
    [moveStatistics setObject:playerStats=[NSMutableDictionary dictionary] forKey:key];
    [playerStats setObject:[NSNumber numberWithInt:0] forKey:@"numberOfMoves"];
    [playerStats setObject:[NSNumber numberWithDouble:0.0] forKey:@"totalMovesPerSecond"];
  }
  [playerStats setObject:[NSNumber numberWithInt:1+[[playerStats objectForKey:@"numberOfMoves"] intValue]]
                  forKey:@"numberOfMoves"];
  [playerStats setObject:[NSNumber numberWithDouble:movesPerSecond+[[playerStats objectForKey:@"totalMovesPerSecond"] doubleValue]]
                  forKey:@"totalMovesPerSecond"];

}

-(double)averageMovesPerSecondForPlayer:(int)pnum {
  id key = [NSNumber numberWithInt:pnum];
  NSMutableDictionary *playerStats = [moveStatistics objectForKey:key];
  int moves = [[playerStats objectForKey:@"numberOfMoves"] intValue];
  double totalMPS = [[playerStats objectForKey:@"totalMovesPerSecond"] doubleValue];
  return (moves>0) ? totalMPS/moves : 0;
}

-(void)run {
  int iters = [[NSUserDefaults standardUserDefaults] integerForKey:@"AutoplayRounds"];
  int i;
  NSString *saveDir = [[NSUserDefaults standardUserDefaults] objectForKey:@"AutoplaySaveDirectory"];
  int maxmoves = [[NSUserDefaults standardUserDefaults] integerForKey:@"AutoplayMaxMoves"];
  if (maxmoves==0) maxmoves = 500;
  for(i=0; i<iters; i++) {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    int moves = 0;
    int winner = 0;
    NSLog(@"Starting game %d", i+1);
    [self setGameState:[self createGameState]];
    while (![[gameState currentGame] isGameOver] && moves<maxmoves) {
      [[self gameState] makeAIMove];
      moves++;
    }
    winner = [[[self gameState] currentGame] winningPlayer];
    [self incrementWinsForPlayer:winner];
    NSLog(@"Finished game %d, winner is %d. Current record %d-%d-%d.", i+1, winner,
          [[playerWins objectForKey:[NSNumber numberWithInt:1]] intValue],
          [[playerWins objectForKey:[NSNumber numberWithInt:2]] intValue],
          [[playerWins objectForKey:[NSNumber numberWithInt:0]] intValue]);
    if (saveDir!=nil) {
      id gamePlist = [[self gameState] propertyList];
      NSString *file = [saveDir stringByAppendingPathComponent:[NSString stringWithFormat:@"%d.ggame", i+1]];
      [gamePlist writeToFile:file atomically:YES];
    }
    [pool release];
  }
  NSLog(@"Player 1 wins:%d; Player 2 wins:%d; Ties:%d",
        [[playerWins objectForKey:[NSNumber numberWithInt:1]] intValue],
        [[playerWins objectForKey:[NSNumber numberWithInt:2]] intValue],
        [[playerWins objectForKey:[NSNumber numberWithInt:0]] intValue]);
  NSLog(@"Average moves evaluated per second: %0.3lf %0.3lf", [self averageMovesPerSecondForPlayer:1], [self averageMovesPerSecondForPlayer:2]);
}

// called when we have an AI move
-(void)aiComputedMoveInfo:(NSNotification *)notification {
  NSDictionary *moveInfo = [notification userInfo];
  NSArray *move = [moveInfo objectForKey:@"move"];

  [self recordStatistics:moveInfo forPlayer:[[self gameState] currentPlayerNumber]];
  [[[self gameState] gameHistory] recordAndExecuteMove:move];
}

@end
