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

@implementation GameHistory

-(id)init {
  self = [super init];
  gameStates = [[NSMutableArray alloc] init];
  stateIndex = 0;
  return self;
}

-(id)initWithGameConfiguration:(GameConfiguration *)gameConfig {
  if ([self init]) {
    NSMutableDictionary *firstState = [NSMutableDictionary dictionary];
    [self setGameConfiguration:gameConfig];
    [firstState setObject:[gameConfig initialGame] forKey:@"game"];
    [gameStates addObject:firstState];
  }
  return self;
}

-(void)dealloc {
  [gameStates release];
  [super dealloc];
}

idAccessor(gameConfiguration, setGameConfiguration)

-(Game *)currentGame {
  return [[gameStates objectAtIndex:stateIndex] objectForKey:@"game"];
}
-(Game *)initialGame {
  return [[gameStates objectAtIndex:0] objectForKey:@"game"];
}

-(void)recordAndExecuteMove:(NSArray *)move {
  Game *newGame = [[[self currentGame] copy] autorelease];
  // remove all states past recordedStateIndex
  while (stateIndex+1<[gameStates count]) {
    [gameStates removeLastObject];
  }
  // add the move to the last state
  // use an empty array instead of nil
  if (move==nil) move = [NSArray array];
  [[gameStates lastObject] setObject:AUTORELEASE([move copy]) forKey:@"move"];
  // execute the move
  [newGame makeMoveSequence:move];
  // add the new game state and advance index to point to it
  [gameStates addObject:[NSMutableDictionary dictionaryWithObject:newGame forKey:@"game"]];
  ++stateIndex;
  
  // send notification?
}

-(int)_previousStateIndexWithPlayerNumberInArray:(NSArray *)pnums {
  int index = stateIndex;
  while (index>0) {
    Game *previousGame = [[gameStates objectAtIndex:--index] objectForKey:@"game"];
    if ([pnums containsObject:[NSNumber numberWithInt:[previousGame currentPlayerNumber]]]) {
      return index;
    }
  }
  return -1;
}
-(int)_nextStateIndexWithPlayerNumberInArray:(NSArray *)pnums {
  int index = stateIndex;
  int max = [gameStates count]-1;
  while (index<max) {
    Game *nextGame = [[gameStates objectAtIndex:++index] objectForKey:@"game"];
    if ([pnums containsObject:[NSNumber numberWithInt:[nextGame currentPlayerNumber]]]) {
      return index;
    }
  }
  return -1;
}

-(BOOL)undoMove {
  if (stateIndex>0) {
    --stateIndex;
    return YES;
  }
  return NO;
}
-(BOOL)canUndoMove {
  return (stateIndex>0);
}

-(BOOL)undoMovesUntilPlayerNumberInArray:(NSArray *)pnums {
  int index = [self _previousStateIndexWithPlayerNumberInArray:pnums];
  if (index>=0) {
    stateIndex = index;
    return YES;
  }
  return NO;
}
-(BOOL)canUndoMovesUntilPlayerNumberInArray:(NSArray *)pnums {
  return ([self _previousStateIndexWithPlayerNumberInArray:pnums]>=0);
}

-(BOOL)redoMove {
  if (stateIndex<[gameStates count]-1) {
    ++stateIndex;
    return YES;
  }
  return NO;
}
-(BOOL)canRedoMove {
  return (stateIndex<[gameStates count]-1);
}

-(BOOL)redoMovesUntilPlayerNumberInArray:(NSArray *)pnums {
  int index = [self _nextStateIndexWithPlayerNumberInArray:pnums];
  if (index>0) {
    stateIndex = index;
    return YES;
  }
  return NO;
}
-(BOOL)canRedoMovesUntilPlayerNumberInArray:(NSArray *)pnums {
  return ([self _nextStateIndexWithPlayerNumberInArray:pnums]>0);
}

-(int)numberOfMoves {
  return [gameStates count];
}
-(int)currentMoveNumber {
  return stateIndex;
}
-(NSArray *)moveWithNumber:(int)movenum {
  if (movenum>=0 && movenum<[gameStates count]) {
    return [[gameStates objectAtIndex:movenum] objectForKey:@"move"];
  }
  return nil;
}
-(Game *)gameWithNumber:(int)movenum {
  if (movenum>=0 && movenum<[gameStates count]) {
    return [[gameStates objectAtIndex:movenum] objectForKey:@"game"];
  }
  return nil;  
}

-(Game *)previousGame {
  if (stateIndex==0) return nil;
  return [[gameStates objectAtIndex:stateIndex-1] objectForKey:@"game"];
}
-(NSArray *)previousMove {
  if (stateIndex==0) return nil;
  return [[gameStates objectAtIndex:stateIndex-1] objectForKey:@"move"];  
}

-(id)propertyList {
  NSMutableDictionary *plist = [NSMutableDictionary dictionary];
  [plist setObject:[[self gameConfiguration] propertyList] forKey:@"configuration"];
  [plist setObject:[[NSNumber numberWithInt:[self currentMoveNumber]] stringValue] forKey:@"moveNumber"];
  {
    NSMutableArray *states = [NSMutableArray array];
    NSEnumerator *se = [gameStates objectEnumerator];
    NSDictionary *state;
    while ((state=[se nextObject])) {
      NSMutableDictionary *stateDict = [NSMutableDictionary dictionary];
      if ([state objectForKey:@"game"]) {
        [stateDict setObject:[[state objectForKey:@"game"] propertyList] forKey:@"game"];
      }
      if ([state objectForKey:@"move"]) {
        // moves are NSArrays of DCHypergridPositions
        NSArray *moveDescArray = [[state objectForKey:@"move"] valuesByObjectsPerformingSelector:@selector(propertyListValue)];
        [stateDict setObject:moveDescArray forKey:@"move"];
      }
      [states addObject:stateDict];
    }
    [plist setObject:states forKey:@"states"];
  }
  return plist;
}
-(id)initFromPropertyList:(id)plist {
  if ([self init]) {
    stateIndex = [[plist objectForKey:@"moveNumber"] intValue];
    [self setGameConfiguration:[[[GameConfiguration alloc] initFromPropertyList:[plist objectForKey:@"configuration"]] autorelease]];
    {
      NSEnumerator *se = [[plist objectForKey:@"states"] objectEnumerator];
      NSDictionary *archivedState;
      while ((archivedState=[se nextObject])) {
        NSMutableDictionary *state = [NSMutableDictionary dictionary];
        if ([archivedState objectForKey:@"game"]) {
          Game *game = [[self gameConfiguration] gameInStartingPosition];
          [game updateFromPropertyList:[archivedState objectForKey:@"game"]];
          [state setObject:game forKey:@"game"];
        }
        if ([archivedState objectForKey:@"move"]) {
          NSArray *movePositions = [DCHypergridPosition positionArrayFromPropertyListValueArray:[archivedState objectForKey:@"move"]];
          [state setObject:movePositions forKey:@"move"];
        }
        [gameStates addObject:state];
      }
    }
  }
  return self;
}

@end
