/* 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 "DCHypergridPosition.h"
#include <string.h>
#include <stdio.h>
#include "hypergrid.h"
#include "string.h"


static DCHypergridPosition **_cachedPositions = NULL;
static int CACHE_MIN = -25;
static int CACHE_MAX = +25;
static int CACHE_SIZE = 50;

// private subclasses used for cached positions to avoid retains and releases

@interface DCArrayWithCachedPosition : NSArray {
  id position;
}
@end

@implementation DCArrayWithCachedPosition

-(id)initWithPosition:(id)pos {
  self = [super init];
  position = pos;
  return self;
}

// this initializer is needed for GNUstep
#ifdef GNUSTEP
-(id)initWithObjects:(id *)objects count:(unsigned)count {
  // GNUstep calls this from -[NSArray init] with arguments of nil and 0
  if (count==0) return self;
  else [NSException raise:@"IndexOutOfBounds" format:@"%@: count (%d) must be 0 for %@",
    NSStringFromSelector(_cmd), index, NSStringFromClass([self class])];
  return nil;
}
#endif

-(unsigned)count {
  return 1;
}

-(id)objectAtIndex:(unsigned)index {
  if (index==0) return position;
  else [NSException raise:@"IndexOutOfBounds" format:@"%@: index (%d) must be 0 for %@",
    NSStringFromSelector(_cmd), index, NSStringFromClass([self class])];
  return nil;
}

-(id)retain {
  return self;
}
-(void)release {
  return;
}
-(id)autorelease {
  return self;
}

@end


@interface DCCachedHypergridPosition : DCHypergridPosition {
  NSArray *array;
}
@end

@implementation DCCachedHypergridPosition : DCHypergridPosition

-(id)retain {
  return self;
}
-(void)release {
  return;
}
-(id)autorelease {
  return self;
}

-(NSArray *)arrayWithSelf_ {
  if (!array) {
    array = [[DCArrayWithCachedPosition alloc] initWithPosition:self];
  }
  return array;
}

@end

@implementation DCHypergridPosition

-(id)initWithSize:(int)cap {
  _numberOfDimensions = cap;
  _data = (int *)calloc(cap, sizeof(int));
  return self;
}

-(id)initWithSize:(int)cap data:(int *)values {
  _numberOfDimensions = cap;
  _data = (int *)calloc(cap, sizeof(int));
  memcpy(_data, values, cap*(sizeof(int)));
  return self;
}

-(id)initWithRow:(int)r column:(int)c {
  int values[] = {r,c};
  return [self initWithSize:2 data:values];
}

+(void)_fillCache {
  if (!_cachedPositions) {
    int r,c;
    int index=0;
    int numCachedPositions = CACHE_SIZE*CACHE_SIZE;
    _cachedPositions = (DCHypergridPosition **)malloc(numCachedPositions*sizeof(DCHypergridPosition *));
    for(r=0; r<CACHE_SIZE; r++) {
      for(c=0; c<CACHE_SIZE; c++) {
        _cachedPositions[index] = [[DCCachedHypergridPosition alloc] initWithRow:CACHE_MIN+r
                                                                          column:CACHE_MIN+c];
        [_cachedPositions[index] arrayWithSelf_]; // create all the cached arrays here
        index++;
      }
    }
    _cachedPositions += (-CACHE_MIN*(CACHE_SIZE+1));
  }
  //return _cachedPositions[(row-CACHE_MIN)*CACHE_SIZE+(col-CACHE_MIN)];
  //return _cachedPositions[row*CACHE_SIZE+col];
}

+(DCHypergridPosition *)positionWithSize:(int)size data:(int *)values {
  if (size==2 && values[0]>=CACHE_MIN && values[0]<CACHE_MAX
              && values[1]>=CACHE_MIN && values[1]<CACHE_MAX) {
    if (!_cachedPositions) [self _fillCache];
    return _cachedPositions[values[0]*CACHE_SIZE+values[1]];
    //return [self _cachedPositionWithRow:values[0] column:values[1]];
  }
  return [[[self alloc] initWithSize:size data:values] autorelease];
}

+(DCHypergridPosition *)positionWithRow:(int)r column:(int)c {
  if (r>=CACHE_MIN && r<CACHE_MAX && c>=CACHE_MIN && c<CACHE_MAX) {
    if (!_cachedPositions) [self _fillCache];
    return _cachedPositions[r*CACHE_SIZE+c];
    //return [self _cachedPositionWithRow:r column:c];
  }
  return [[[self alloc] initWithRow:r column:c] autorelease];
}

-(id)copyWithZone:(NSZone *)zone {
  return [self retain];
}

-(void)dealloc {
  free(_data);
  [super dealloc];
}

-(int)numberOfDimensions {
  return _numberOfDimensions;
}

-(int)valueAtIndex:(int)index {
  return _data[index];
}

-(id)setValue:(int)value atIndex:(int)index {
  _data[index] = value;
  return self;
}

-(BOOL)isEqual:(id)object {
  return ([object isKindOfClass:[self class]] &&
          [self numberOfDimensions]==[object numberOfDimensions] &&
          memcmp([self cArray], [object cArray], [self numberOfDimensions]*sizeof(int))==0);
}

-(unsigned)hash {
  int factor = 37;
  int d = [self numberOfDimensions];
  unsigned h = 0;
  int i;
  for(i=0; i<d; i++) {
    h = factor*h + [self valueAtIndex:i];
  }
  return h;
}

/** Used to order positions lexicographically. Returns NSOrderedAscending if the argument's value
is greater than the receiver's, NSOrderedSame if they're equal, and NSOrderedDescending if the
argument's value is less than the receiver's. Raises an exception if the argument and receiver
have different numbers of dimensions.
*/
-(int)compare:(DCHypergridPosition *)pos {
  int d1 = [self numberOfDimensions];
  int d2 = [pos  numberOfDimensions];
  int i;
  if (d1!=d2) {
    [NSException raise:@"Illegal argument" format:@"different number of dimensions (%d and %d)",d1,d2];
  }
  for(i=0; i<d1; i++) {
    int v1 = [self valueAtIndex:i];
    int v2 = [pos  valueAtIndex:i];
    if (v2>v1) return NSOrderedAscending;
    if (v2<v1) return NSOrderedDescending;
  }
  return NSOrderedSame;
}

-(int)row {
  return _data[0];
}

-(int)column {
  return _data[1];
}

-(DCHypergridPosition *)positionByAddingPosition:(DCHypergridPosition *)pos {
  int dim = [self numberOfDimensions];
  id result = nil;
  if (dim==2) {
    result = [DCHypergridPosition positionWithRow:[self row]+[pos row] column:[self column]+[pos column]];
  }
  else {
    int *data = array_add([self cArray], [pos cArray], dim);
    result = [DCHypergridPosition positionWithSize:dim data:data];
    free(data);
  }
  return result;
}

-(DCHypergridPosition *)positionBySubtractingPosition:(DCHypergridPosition *)pos {
  int dim = [self numberOfDimensions];
  id result = nil;
  if (dim==2) {
    result = [DCHypergridPosition positionWithRow:[self row]-[pos row] column:[self column]-[pos column]];
  }
  else {
    int *data = array_subtract([self cArray], [pos cArray], dim);
    result = [DCHypergridPosition positionWithSize:dim data:data];
    free(data);
  }
  return result;
}

-(int *)cArray {
  return _data;
}

-(id)propertyListValue {
  NSMutableArray *array = [NSMutableArray array];
  int i;
  for(i=0; i<_numberOfDimensions; i++) {
    [array addObject:[NSString stringWithFormat:@"%d",_data[i]]];
  }
  return [array componentsJoinedByString:@" "];
}
+(DCHypergridPosition *)positionWithPropertyListValue:(id)value {
  NSArray *coordStrings = [value componentsSeparatedByString:@" "];
  int *data = (int *)malloc([coordStrings count]*sizeof(int));
  id result;
  int i;
  for(i=0; i<[coordStrings count]; i++) {
    data[i] = [[coordStrings objectAtIndex:i] intValue];
  }
  result = [self positionWithSize:[coordStrings count] data:data];
  free(data);
  return result;
}

+(NSArray *)positionArrayFromPropertyListValueArray:(NSArray *)values {
  NSMutableArray *positions = [NSMutableArray array];
  NSEnumerator *ve = [values objectEnumerator];
  id val;
  while (val=[ve nextObject]) {
    [positions addObject:[self positionWithPropertyListValue:val]];
  }
  return positions;
}

-(void)debug {
  int i;
  printf("[");
  for(i=0; i<_numberOfDimensions; i++) {
    printf("%4d", _data[i]);
  }
  printf("]\n");
}

-(NSString *)description {
  NSMutableArray *array = [NSMutableArray array];
  int i;
  for(i=0; i<_numberOfDimensions; i++) {
    [array addObject:[NSString stringWithFormat:@"%d",_data[i]]];
  }
  return [NSString stringWithFormat:@"[%@]",[array componentsJoinedByString:@","]];
}

@end
