//
//  ICFGameViewController.m
//  WhackACac
//
//  Created by Kyle Richter on 7/2/12.
//  Copyright (c) 2012 Dragon Forged Software. All rights reserved.
//

#import "ICFGameViewController.h"

#define kLifeImageTag 100

#define kGameOverAlert 1
#define kPauseAlert 2

@implementation ICFGameViewController

- (void)viewDidLoad
{
    [[ICFGameCenterManager sharedManager] setDelegate: self];
    
    score = 0;
    life = 5;
    gameOver = NO;
    paused = NO;
    
    [super viewDidLoad];
    
    [self updateLife];
        
    //make one cactus right away
    [self performSelector: @selector(spawnCactus)];
    [self performSelector:@selector(spawnCactus) withObject:nil afterDelay:1.0];
    
    play5MinTimer = [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(play5MinTick) userInfo:nil repeats:YES];
    
    [GKAchievementDescription loadAchievementDescriptionsWithCompletionHandler:^(NSArray *descriptions, NSError *error)
     {
         
         if(error != nil)
         {
             NSLog(@"Wystąpił błąd w trakcie wczytywania osiagnięć: %@", [error localizedDescription]);
         }
         
         
         for(GKAchievementDescription *achievementDescription in descriptions)
         {
             NSLog(@"%@", achievementDescription);
         }
             
     }];

}

-(void)viewWillDisappear:(BOOL)animated
{
    GKAchievement *play5MatchesAchievement = [[ICFGameCenterManager sharedManager] achievementForIdentifier:@"com.dragonforged.whackacac.play5"];

    if(![play5MatchesAchievement isCompleted])
    {    
        double matchesPlayed = [play5MatchesAchievement percentComplete]/20.0f;
        matchesPlayed++;
        
        [[ICFGameCenterManager sharedManager] reportAchievement:@"com.dragonforged.whackacac.play5" withPercentageComplete: matchesPlayed*20.0f];
    }
    
    [super viewWillDisappear: animated];
}

#pragma mark -
#pragma mark Actions

- (IBAction)pause:(id)sender 
{
    paused = YES;
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"Wstrzymano grę!" delegate:self cancelButtonTitle:@"Zakończ" otherButtonTitles:@"Powróć", nil];
    alert.tag = kPauseAlert;
    [alert show];
}

#pragma mark -
#pragma mark Game Play

- (void)spawnCactus;
{
    if(gameOver)
    {
        return;
    }
    
    if(paused)
    {
        [self performSelector:@selector(spawnCactus) withObject:nil afterDelay:1];
        return;
    }
    
    int rowToSpawnIn = arc4random()%3;
    int horizontalLocation = (arc4random()%1024);
        
    int cactusSize = arc4random()%3;
    UIImage *cactusImage = nil;
    
    switch (cactusSize) 
    {
        case 0:
            cactusImage = [UIImage imageNamed: @"CactusLarge.png"];
            break;
        case 1:
            cactusImage = [UIImage imageNamed: @"CactusMed.png"];
            break;
        case 2:
            cactusImage = [UIImage imageNamed: @"CactusSmall.png"];
            break;
        default:
            break;
    }
    
    if(horizontalLocation > 1024 - cactusImage.size.width)
        horizontalLocation = 1024 - cactusImage.size.width;
        
    UIImageView *duneToSpawnBehind = nil;
    
    switch (rowToSpawnIn) 
    {
        case 0:
            duneToSpawnBehind = duneOne;
            break;
        case 1:
            duneToSpawnBehind = duneTwo;
            break;
        case 2:
            duneToSpawnBehind = duneThree;
            break;
        default:
            break;
    }
                         
    float cactusHeight = cactusImage.size.height;
    float cactusWidth = cactusImage.size.width;

    UIButton *cactus = [[UIButton alloc] initWithFrame:CGRectMake(horizontalLocation, (duneToSpawnBehind.frame.origin.y), cactusWidth, cactusHeight)];
    [cactus setImage:cactusImage forState: UIControlStateNormal];
    [cactus addTarget:self action:@selector(cactusHit:) forControlEvents:UIControlEventTouchDown];
    [self.view insertSubview:cactus belowSubview:duneToSpawnBehind];
    
    [UIView beginAnimations: @"slideInCactus" context:nil];
    [UIView setAnimationCurve: UIViewAnimationCurveEaseInOut];
    [UIView setAnimationDuration: 0.25];
    cactus.frame = CGRectMake(horizontalLocation, (duneToSpawnBehind.frame.origin.y)-cactusHeight/2, cactusWidth, cactusHeight);
    [UIView commitAnimations];
    
    [self performSelector:@selector(cactusMissed:) withObject:cactus afterDelay:2.0];
    
}

- (void)cactusMissed:(UIButton *)sender;
{
    if([sender superview] == nil)
    {
        return;
    }
    
    if(paused)
    {
        return;
    }
    
    
    CGRect frame = sender.frame;
    frame.origin.y += sender.frame.size.height;
    
    
    [UIView animateWithDuration:0.1
                          delay:0.0
                        options: UIViewAnimationCurveLinear | UIViewAnimationOptionBeginFromCurrentState
                     animations:^
     {
         sender.frame = frame;     
     } 
                     completion:^(BOOL finished)
     {
         [sender removeFromSuperview];
         [self performSelector:@selector(spawnCactus) withObject:nil afterDelay:(arc4random()%3) + .5];
         life--;
         [self updateLife];
     }];
}

- (IBAction)cactusHit:(id)sender;
{
    [UIView animateWithDuration:0.1
                          delay:0.0
                        options: UIViewAnimationCurveLinear | UIViewAnimationOptionBeginFromCurrentState
                     animations:^
                     {
                        [sender setAlpha: 0];
                     } 
                     completion:^(BOOL finished)
                     {
                         [sender removeFromSuperview];
                     }];
    
    score++;
    
    [self displayNewScore: score];
    
    GKAchievement *killOneAchievement = [[ICFGameCenterManager sharedManager] achievementForIdentifier:@"com.dragonforged.whackacac.killone"];
    
    if(![killOneAchievement isCompleted])
    {
        [[ICFGameCenterManager sharedManager] reportAchievement:@"com.dragonforged.whackacac.killone" withPercentageComplete:100.00];
    }
    
    GKAchievement *killOneThousandAchievement = [[ICFGameCenterManager sharedManager] achievementForIdentifier:@"com.dragonforged.whackacac.1000whacks"];
    
    double localKills = [[[NSUserDefaults standardUserDefaults] objectForKey:@"kills"] doubleValue];
    double remoteKills = [killOneThousandAchievement percentComplete] * 10.0;
   
    if(remoteKills > localKills)
    {
        localKills = remoteKills;
    }
    
    localKills++;
    
    if(localKills <= 1000)
    {
        if(localKills <= 100)
        {
            [[ICFGameCenterManager sharedManager] reportAchievement:@"com.dragonforged.whackacac.100whacks" withPercentageComplete:localKills];
        }
        
        [[ICFGameCenterManager sharedManager] reportAchievement:@"com.dragonforged.whackacac.1000whacks" withPercentageComplete:(localKills/10.0)];
    }
    
    [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithDouble: localKills] forKey:@"kills"];

    [self performSelector:@selector(spawnCactus) withObject:nil afterDelay:(arc4random()%3) + .5];
}

-(void)updateLife
{
    UIImage *lifeImage = [UIImage imageNamed:@"heart.png"];
    
    for(UIView *view in [self.view subviews])
    {
        if(view.tag == kLifeImageTag)
        {
            [view removeFromSuperview];
        }
    }
    
    
    for (int x = 0; x < life; x++)
    {
        UIImageView *lifeImageView = [[UIImageView alloc] initWithImage: lifeImage];
        lifeImageView.tag = kLifeImageTag;
        
        CGRect frame = lifeImageView.frame;
        frame.origin.x = 985 - (x * 30);
        frame.origin.y = 20;
        lifeImageView.frame = frame;
    
        [self.view addSubview: lifeImageView];
    }

    if(life == 0)
    {
        //report score
        [[ICFGameCenterManager sharedManager] reportScore: (int64_t)score forCategory:@"com.dragonforged.whackacac.leaderboard"];
        
        gameOver = YES;
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Game Over!" message: [NSString stringWithFormat: @"You scored %0.0f points!", score] delegate:self cancelButtonTitle:@"Dismiss" otherButtonTitles:nil];
        alert.tag = kGameOverAlert;
        [alert show];
    }
}

- (void)displayNewScore:(float)updatedScore;
{
    int scoreInt = score;
    
    if(scoreInt % 10 == 0 && score <= 50)
    {
        [self spawnCactus];
    }
    
    scoreLabel.text = [NSString stringWithFormat: @"%06.0f", updatedScore];
    
    GKAchievement *score100Achievement = [[ICFGameCenterManager sharedManager] achievementForIdentifier:@"com.dragonforged.whackacac.score100"];
    
    if(![score100Achievement isCompleted])
    {
        [[ICFGameCenterManager sharedManager] reportAchievement:@"com.dragonforged.whackacac.score100" withPercentageComplete:score];
    }
}

- (void)play5MinTick;
{
    if(paused || gameOver)
    {
        return;
    }
    
    GKAchievement *play5MinAchievement = [[ICFGameCenterManager sharedManager] achievementForIdentifier:@"com.dragonforged.whackacac.play5Mins"];
    
    if([play5MinAchievement isCompleted])
    {
        [play5MinTimer invalidate];
        play5MinTimer = nil;
        return;
    }
    
    double percentageComplete = play5MinAchievement.percentComplete + 1.0;
    
    [[ICFGameCenterManager sharedManager] reportAchievement:@"com.dragonforged.whackacac.play5Mins" withPercentageComplete:percentageComplete];
}

#pragma mark -
#pragma mark UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(alertView.tag == kGameOverAlert)
    {
        [self.navigationController popViewControllerAnimated: YES];
    }
    
    else if (alertView.tag == kPauseAlert)
    {
        if(buttonIndex == 0) //exit
        {
            //report score
            [[ICFGameCenterManager sharedManager] reportScore: (int64_t)score forCategory:@"com.dragonforged.whackacac.leaderboard"];

            [self.navigationController popViewControllerAnimated: YES];
        }
        else //resume
        {
            paused = NO;
        }
    }
}



#pragma mark -
#pragma mark GameCenterManagerDelegate

-(void)gameCenterScoreReported:(NSError *)error;
{
    if(error != nil)
    {
		NSLog(@"Wystąpił błądd w trakcie zgłaszania wyniku do Game Center: %@", [error localizedDescription]);
    }
    
    else
    {
        NSLog(@"Wysłano wynik");
    }
}

-(void)gameCenterAchievementReported:(NSError *)error;
{
    if(error != nil)
    {
		NSLog(@"W trakcie zgłaszania osiągnięcia do Game Center wystąpił błąd: %@", [error localizedDescription]);
    }
    
    else
    {
        NSLog(@"Zaktualizowano osiągnięcie!");
    }
}

#pragma mark -
#pragma mark Cleanup

- (void)viewDidUnload 
{
    scoreLabel = nil;
    duneOne = nil;
    duneTwo = nil;
    duneThree = nil;
    [super viewDidUnload];
}


@end
