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

static NSArray *gGameList = nil;


@implementation NSDictionary(GameConfiguration_DisplayName)
-(NSString *)displayName_ {
  NSString *result = [self objectForKey:@"displayName"];
  if (result) return result;
  return [self objectForKey:@"name"];
}
@end

@implementation GameConfiguration

+(NSArray *)gameList {
  if (!gGameList) {
    gGameList = [[[NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Games" ofType:@"plist"]] sortedArrayUsingKey_:@"name"] retain];
  }
  return gGameList;
}

+(NSDictionary *)dictionaryForGameWithName:(NSString *)name {
  return [[self gameList] objectWithValue:name
                              forSelector:@selector(objectForKey:)
                             withArgument:@"name"];
}

-(NSDictionary *)gameDictionary {
  return [[self class] dictionaryForGameWithName:[self gameName]];
}
-(NSDictionary *)dictionaryForVariation {
  NSArray *variations = [[self gameDictionary] objectForKey:@"variations"];
  return [variations objectWithValue:[self variationName]
                         forSelector:@selector(objectForKey:)
                        withArgument:@"name"];
}

idAccessor(initialGame, setInitialGame)

-(id)initWithName:(NSString *)name variation:(NSString *)variation {
  NSArray *varNames;
  self = [super init];
  gameName = [name copy];
  varNames = [self allVariationNames];
  if (!variation) {
    // look for default
    variation = [[Preferences sharedInstance] configurationForGame:gameName];
  }
  if (![varNames containsObject:variation]) {
    variation = nil;
  }
  if (!variation) {
    // if not specified and no default, or if nonexistent, use first
    if ([varNames count]>0) variation = [varNames objectAtIndex:0];
  }
  variationName = [variation copy];
  [self createNewInitialGame];
  return self;
}

/*
+(GameConfiguration *)configurationWithDisplayName:(NSString *)name
                              variationDisplayName:(NSString *)variation {
}
*/

+(GameConfiguration *)configurationFromDefaults {
  NSString *initialGameName = [[Preferences sharedInstance] initialGame];
  NSDictionary *gameDict;
  NSString *varname = nil;
  if (!initialGameName) initialGameName = [[[self gameList] objectAtIndex:0] objectForKey:@"name"];
  gameDict = [self dictionaryForGameWithName:initialGameName];
  if (!gameDict) {
    // invalid game name, default to first
    initialGameName = [[[self gameList] objectAtIndex:0] objectForKey:@"name"];
    gameDict = [self dictionaryForGameWithName:initialGameName];
  }
  // see if game has variations, if so read from prefs or default to first
  if ([[gameDict objectForKey:@"variations"] count]>0) {
    varname = [[Preferences sharedInstance] configurationForGame:initialGameName];
    if (nil==varname || ![[[gameDict objectForKey:@"variations"] valuesByObjectsPerformingSelector:@selector(objectForKey:) withObject_:@"name"] containsObject:varname]) {
      // variation missing or invalid, use first
      varname = [[[gameDict objectForKey:@"variations"] objectAtIndex:0] objectForKey:@"name"];
    }
  }
  return [[[self alloc] initWithName:initialGameName variation:varname] autorelease];
}

-(void)saveToDefaults {
  [[Preferences sharedInstance] setInitialGame:[self gameName]];
  [[Preferences sharedInstance] setConfiguration:[self variationName] forGame:[self gameName]];
}

-(void)dealloc {
  [gameName release];
  [variationName release];
  [self setInitialGame:nil];
  
  [super dealloc];
}

-(NSString *)gameName {
  return gameName;
}
-(NSString *)variationName {
  return variationName;
}

// FIXME
-(NSString *)gameDisplayName {
  return gameName;
}
-(NSString *)variationDisplayName {
  return variationName;
}

-(Class)gameClass {
  NSString *className = [[self gameDictionary] objectForKey:@"class"];
  return NSClassFromString(className);  
}

-(Game *)gameInStartingPosition {
  Game *game = [[[[self gameClass] alloc] init] autorelease];
  [game setConfigurationInfo:[[self dictionaryForVariation] objectForKey:@"params"]];
  [game reset];
  return game;
}

-(void)createNewInitialGame {
  [self setInitialGame:[self gameInStartingPosition]];
}

-(id)aiWithName:(NSString *)aiName {
  NSDictionary *dict = [[[self gameDictionary] objectForKey:@"aiTypes"] objectWithValue:aiName
                                                            forSelector:@selector(objectForKey:)
                                                                           withArgument:@"name"];
  NSString *aiClassName = [dict objectForKey:@"class"];
  NSDictionary *aiParams = [dict objectForKey:@"params"];
  GenericAI *ai = (aiClassName) ? [[[NSClassFromString(aiClassName) alloc] init] autorelease] : nil;
  if (aiParams) {
    [ai takeValuesFromDictionary:aiParams];
    [ai setName:aiName];
  }
  return ai;
}

-(id)viewDelegate {
  NSString *className = [[self gameDictionary] objectForKey:@"viewDelegate"];
  if (className) {
    id delegate = [[[NSClassFromString(className) alloc] init] autorelease];
    if ([[self gameDictionary] objectForKey:@"viewDelegateParams"]) {
      [delegate takeValuesFromDictionary:[[self gameDictionary] objectForKey:@"viewDelegateParams"]];
    }
    return delegate;
  } 
  return nil;
}

+(NSArray *)allGameDisplayNames {
  return [[self gameList] valuesByObjectsPerformingSelector:@selector(displayName_)];
}
+(NSArray *)allGameNames {
  return [[self gameList] valuesByObjectsPerformingSelector:@selector(objectForKey:) withObject_:@"name"];
}

-(NSArray *)allVariationDisplayNames {
  NSArray *variations = [[self gameDictionary] objectForKey:@"variations"];
  return [variations valuesByObjectsPerformingSelector:@selector(displayName_)];
}
-(NSArray *)allVariationNames {
  NSArray *variations = [[self gameDictionary] objectForKey:@"variations"];
  return [variations valuesByObjectsPerformingSelector:@selector(objectForKey:) withObject_:@"name"];
}

-(NSArray *)allAINames {
  NSArray *aiTypes = [[self gameDictionary] objectForKey:@"aiTypes"];
  return [aiTypes valuesByObjectsPerformingSelector:@selector(objectForKey:) withObject_:@"name"];
}
-(NSArray *)allAIDisplayNames {
  NSArray *aiTypes = [[self gameDictionary] objectForKey:@"aiTypes"];
  return [aiTypes valuesByObjectsPerformingSelector:@selector(displayName_)];
}

-(id)propertyList {
  NSMutableDictionary *dict = [NSMutableDictionary dictionary];
  [dict setObject:[self gameName] forKey:@"game"];
  if ([self variationName]) [dict setObject:[self variationName] forKey:@"variation"];
  if ([self initialGame]) [dict setObject:[[self initialGame] propertyList] forKey:@"initialGame"];
  return dict;
}
-(id)initFromPropertyList:(id)plist {
  [self initWithName:[plist objectForKey:@"game"] variation:[plist objectForKey:@"variation"]];
  if ([plist objectForKey:@"initialGame"]) [[self initialGame] updateFromPropertyList:[plist objectForKey:@"initialGame"]];
  return self;
}


@end
