//
//  HelloWorldLayer.m
//  Caterpillar
//
//  Created by Brandon Trebitowski on 11/11/11.
//  Copyright __MyCompanyName__ 2011. All rights reserved.
//

#import "GameLayer.h"
#import "Sprout.h"
#import "Player.h"
#import "Caterpillar.h"

@interface GameLayer(Private)
- (CGPoint)randomEmptyLocation;
- (void)placeRandomSprout;
@end

@implementation GameLayer

@synthesize spritesBatchNode = _spritesBatchNode;
@synthesize sprouts = _sprouts;
@synthesize level = _level;
@synthesize player = _player;
@synthesize livesSprites = _livesSprites;
@synthesize playerScoreLabel = _playerScoreLabel;
@synthesize caterpillars = _caterpillars;

+(CCScene *) scene {
	CCScene *scene = [CCScene node];
	
	GameLayer *layer = [GameLayer node];
	
	[scene addChild: layer];
	
	return scene;
}

- (void) dealloc {
    [_spritesBatchNode release];
    [_sprouts release];
    [_player release];
    [_livesSprites release];
    [_caterpillars release];
	[super dealloc];
}

-(id) init {
	if( (self=[super init])) {
        
        [CCTexture2D setDefaultAlphaPixelFormat:kCCTexture2DPixelFormat_RGBA4444];
        
	    // 1.  
        self.spritesBatchNode = [CCSpriteBatchNode batchNodeWithFile:@"caterpillar.png"];
        [self addChild:self.spritesBatchNode];
	    // 2.
        [[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"caterpillar.plist"];
        
        [CCTexture2D setDefaultAlphaPixelFormat:kCCTexture2DPixelFormat_RGB565];        
        // 3.
	    CCSprite * background = [CCSprite spriteWithSpriteFrameName:@"background.png"];
        background.anchorPoint = ccp(0,0);
        [self.spritesBatchNode addChild:background];
        
        [CCTexture2D setDefaultAlphaPixelFormat:kCCTexture2DPixelFormat_Default];
        
        // 1
        self.level = 1;
        
        // 2    
        for(int i = 0; i < kRows; i++) {
            for(int j = 0; j < kColumns; j++) {
                _locations[i][j] = NO;
            }
        }
        
        // 3 
        srand(time(NULL));
        _sprouts = [[NSMutableArray alloc] init];
        for(int i = 0; i < kStartingSproutsCount; i++) {
            // 4
            [self placeRandomSprout];
        }
        
        _player = [[Player alloc] initWithGameLayer:self];
        _player.position = ccp(kGameAreaStartX + (kGameAreaWidth / 2), 88);
        _player.lives = kPlayerStartingLives;
        _player.score = 0;   
        
        // init live sprites
        _livesSprites = [[NSMutableArray alloc] init];
        
        // Register for lives notifications
        [[NSNotificationCenter defaultCenter] addObserver:self 
                                                 selector:@selector(updateLives:) 
                                                     name:kNotificationPlayerLives 
                                                   object:nil];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationPlayerLives 
                                                            object:nil];
        
        
        _playerScoreLabel = [[CCLabelTTF labelWithString:@"0" 
                                              dimensions:CGSizeMake(100, 25) 
                                               alignment:UITextAlignmentRight 
                                                fontName:@"Helvetica" 
                                                fontSize:18] retain];
        _playerScoreLabel.position = ccp(254,435);
        [self addChild:_playerScoreLabel];
        
        // Register for score notifications
        [[NSNotificationCenter defaultCenter] addObserver:self 
                                                 selector:@selector(updateScore:) 
                                                     name:kNotificationPlayerScore
                                                   object:nil];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationPlayerScore
                                                            object:nil];
        
        _caterpillars = [[NSMutableArray alloc] init];
        CGPoint startingPosition = ccp(kGameAreaStartX, kGameAreaHeight + kGameAreaStartY - kGridCellSize / 2);
        Caterpillar *caterpillar = [[[Caterpillar alloc] initWithGameLayer:self level:self.level position:startingPosition] autorelease];
        [self.caterpillars addObject:caterpillar];
        
        [self schedule:@selector(update:)];
        
	}
	return self;
}

- (void)update:(ccTime)dt {
    [self.caterpillars enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        Caterpillar *caterpillar = (Caterpillar *)obj;
        [caterpillar update:dt];         
    }];
}

- (void)placeRandomSprout {
    Sprout *sprout = [[[Sprout alloc] initWithGameLayer:self] autorelease];
    // random x within the grass area
    CGPoint p = [self randomEmptyLocation];            
    
    sprout.position = ccp(p.x * kGridCellSize + kGameAreaStartX, 
                          (kGameAreaStartY - kGridCellSize + kGameAreaHeight) - p.y * kGridCellSize - kGridCellSize/2);
    [self.sprouts addObject:sprout];
}

- (CGPoint) randomEmptyLocation {
    
    int column;
    int row;
    BOOL found = NO;
    
    while(!found) {
        column = (arc4random() % kColumns);
        row = (arc4random() % kRows);
        
        if(!_locations[row][column]) {
            found = YES;
            _locations[row][column] = YES;
        }
    }
    
    return CGPointMake(column, row);
}

- (void) updateLives:(NSNotification *) notification {
    NSInteger lifeCount = self.player.lives;
    
    // 1
    [self.livesSprites enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        [self.spritesBatchNode removeChild:obj cleanup:YES];
    }];    
    [self.livesSprites removeAllObjects];
    
    // 2
    for(int i = 0; i < lifeCount; i++) {
        CCSprite *sprite = [CCSprite spriteWithSpriteFrameName:@"player.png"];
        sprite.position = ccp(kGameAreaStartX + (i * kGridCellSize * 2), 435);
        [self.livesSprites addObject:sprite];
        [self.spritesBatchNode addChild:sprite];
    }
    
}

- (void) updateScore:(NSNotification *) notification {
    [self.playerScoreLabel setString:[NSString stringWithFormat:@"%d",self.player.score]]; 
}

@end
