//
//  Caterpillar.m
//  Caterpillar
//
//  Created by Brandon Trebitowski on 11/15/11.
//  Copyright (c) 2011 __MyCompanyName__. All rights reserved.
//

#import "Caterpillar.h"
#import "GameLayer.h"
#import "GameConfig.h"
#import "Segment.h"

@implementation Caterpillar

@synthesize segments = _segments;
@synthesize currentState = _currentState;
@synthesize previousState = _previousState;
@synthesize totalTime = _totalTime;
@synthesize moveCount = _moveCount;
@synthesize level = _level;

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

- (id)initWithGameLayer:(GameLayer *)layer level:(NSInteger)level position:(CGPoint) position {
    if(self = [super initWithGameLayer:layer]) {
        self.segments = [NSMutableArray array];
        self.level = level;
        self.currentState = CSRight;
        self.previousState = CSDownLeft;
        
        // 1
        [super setPosition:position];
        
	    // 2
        int length = kCaterpillarLength + self.level / 2;  
        
        for(int i = 0; i < length; i++) {
            // 1
            Segment *segment = [[[Segment alloc] initWithGameLayer:self.gameLayer] autorelease];
            segment.position = position;
            [self.segments addObject:segment];
        }
        
        __block Segment *parentSegment = [self.segments objectAtIndex:0];
        
        // 2
        [self.segments enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            Segment *segment = (Segment *)obj;            
            
            if(![segment isEqual:parentSegment]) {
                segment.parent = parentSegment;
            }
            
            segment.position = self.position;
            segment.previousPosition = self.position;
            parentSegment = segment;
            
        }];
    }
    return self;
}

- (void)update:(ccTime)dt {
    
    // 1
    self.totalTime += dt;
    if(self.totalTime < 4.0 / (self.level * 2.0)) {
        self.totalTime += dt;
        return;
    } else {
        self.totalTime = 0;
    }
    
	// 2
    __block int x = self.position.x;
    __block int y = self.position.y;
    
    // 3
    x += kGridCellSize;
	// 4
    self.position = ccp(x,y);
    
}

- (void) setPosition:(CGPoint)position {
    // 1
    [super setPosition:position];
    
    // 2
    Segment *head = [self.segments objectAtIndex:0];
    head.position = position;
    
    // 3
    [self.segments enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        Segment *segment = (Segment *)obj;
        if(segment.parent) {
            segment.position = segment.parent.previousPosition;
        }
    }];
}

@end
