//
//  GameScene.m
//  And Unexpected Gift
//
//  Created by Marcos Castro on 1/24/15.
//  Copyright (c) 2015 Marcos Castro. All rights reserved.
//

#import "GameScene.h"
#import <AVFoundation/AVFoundation.h>
#import "GameOver.h"

@implementation GameScene
{
    SKSpriteNode * enemy;
    SKSpriteNode * moneyNode;
    SKSpriteNode * bucket;
    SKShapeNode  * contactNode;
    SKSpriteNode * aux;
    SKSpriteNode * head;
    
    SKSpriteNode * life1;
    SKSpriteNode * life2;
    SKSpriteNode * life3;
    
    NSUserDefaults * RecordsPersist;
    
    SKTexture * diaperTexture;
    SKTexture * shitTexture;
    
    UIGestureRecognizer * pan;
    
    int lives;
    int Records[3];
    
    int money;
    int score;
    BOOL gameOver;
    bool touchBool;
    
    SKLabelNode * moneylabel;
    SKLabelNode * scoreLabel;
    AVAudioPlayer * BG;
    AVAudioPlayer * cry;
    
    SKSpriteNode * bonusNode;
}

static const int PlayerCategory = 1;
static const int DiaperCategory = 2;
static const int MoneyCategory = 3;
static const int BottleCategory = 5;



-(void)didMoveToView:(SKView *)view

{
    self.backgroundColor = [SKColor whiteColor];
    
    
    pan = [[UIPanGestureRecognizer alloc] initWithTarget: self action:@selector(pan:)];
    
    [view addGestureRecognizer:pan];
    
    [self start];
    
    
    
}



-(void)update:(CFTimeInterval)currentTime

{
    [self spawnEnemies:currentTime];
    [self spawnMoney:currentTime];
    [self spawnBonus:currentTime];
    
    [self enumerateChildNodesWithName:@"bottle" usingBlock:^(SKNode *node, BOOL *stop)
     
     {
         SKSpriteNode *bg     = (SKSpriteNode *)node;
         if (!bg)
         {
             [cry stop];
         }
         
     }];
    
    for (SKSpriteNode * k in self.children)
    {
        
        if (k.position.y<50)
        {
            [k removeFromParent];
        }
    }
    
}


-(void) start
{
    
    [self removeAllActions];
    [self removeAllChildren];
    
    touchBool = false;
    gameOver = false;
    
    NSURL* musicFile = [NSURL fileURLWithPath:[[NSBundle mainBundle]                                                                                                                  pathForResource:@"BG" ofType:@"mp3"]];
    
    
    BG               = [[AVAudioPlayer alloc] initWithContentsOfURL:musicFile  error:nil];
    BG.numberOfLoops = -1;
    BG.volume        = 0.3;
    [BG play];//Criação do som de Fundo
    
    SKSpriteNode * Background = [SKSpriteNode spriteNodeWithImageNamed:@"Bg.png"];
    Background.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame));
    [self addChild:Background];
    
    self.physicsWorld.contactDelegate = self;
    
    RecordsPersist = [[NSUserDefaults alloc]init];
    
    NSInteger rcd1 = [[RecordsPersist objectForKey:@"rcd1S"] integerValue];
    NSInteger rcd2= [[RecordsPersist objectForKey:@"rcd2S"] integerValue];
    NSInteger rcd3 = [[RecordsPersist objectForKey:@"rcd3S"] integerValue];
    
    
    Records[0]= rcd1;
    Records[1]= rcd2;
    Records[2]= rcd3;
    
    
    bucket = [SKSpriteNode spriteNodeWithImageNamed:@"Bucket.png"];
    [bucket setScale:0.5];
    bucket.position = CGPointMake(350, 160);
    bucket.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:CGSizeMake(bucket.size.width, bucket.size.height-15)];
    bucket.physicsBody.dynamic = NO;
    bucket.zPosition = 3;
    [self addChild:bucket];
    
    head = [SKSpriteNode spriteNodeWithImageNamed:@"Head.png"];
    head.position = CGPointMake(bucket.position.x, bucket.position.y+100);
    [head setScale:0.6];
    head.zPosition=2;
    [self addChild:head];

    
    
    contactNode = [SKShapeNode node];
    CGPathRef pathT1 = CGPathCreateWithRect(CGRectMake(-30, -10, bucket.size.width-10, 0), nil);
    contactNode.path = pathT1;
    contactNode.alpha = 0;
    contactNode.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:CGSizeMake(bucket.size.width*1.8, 15)];
    contactNode.position = CGPointMake(0, 100);
    contactNode.physicsBody.categoryBitMask= PlayerCategory;
    contactNode.physicsBody.contactTestBitMask = DiaperCategory;
    contactNode.physicsBody.collisionBitMask = 0;
    contactNode.physicsBody.affectedByGravity = NO;
    [bucket addChild:contactNode];
    
    
    money = 20;
    
    moneylabel = [SKLabelNode labelNodeWithFontNamed:@"Chalkduster"];
    moneylabel.position = CGPointMake(100, 620);
    moneylabel.text = @"money: 20";
    moneylabel.fontSize = 30;
    moneylabel.fontColor = [SKColor blackColor];
    
    
    
    score = 0 ;
    scoreLabel = [SKLabelNode labelNodeWithFontNamed:@"Chalkduster"];
    scoreLabel.position = CGPointMake(100, 580);
    scoreLabel.fontColor = [SKColor blackColor];
    
    scoreLabel.text= @"score: 0" ;
    
    [self addChild:moneylabel];
    [self addChild:scoreLabel];
    
    lives = 3;
    
    
    life1 = [SKSpriteNode spriteNodeWithImageNamed:@"heart"];
    life2 = [SKSpriteNode spriteNodeWithImageNamed:@"heart"];
    life3 = [SKSpriteNode spriteNodeWithImageNamed:@"heart"];
    
    NSArray * LivesArray = [NSArray arrayWithObjects:life1, life2, life3, nil];
    
    for (int i=0; i<3; i++)
        
    {
        SKSpriteNode * auxlifes = LivesArray[i];
        
        auxlifes.position = CGPointMake(35+35*i, 550);
        auxlifes.zPosition = 6;
        [auxlifes setScale:0.06];
        
        [self addChild:auxlifes];
        
    }
    
    
    
}
-(void) spawnBonus:(float) time;
{
    
    static float oldTime = 0;
    
    if (oldTime == 0) oldTime = time;
    
    
    
    if (time - oldTime > arc4random()%25+10)
    {
        
        int i = arc4random()%2;
        
        if (i==1)
        {
            bonusNode = [SKSpriteNode spriteNodeWithImageNamed:@"bottle.png"];
            bonusNode.name = @"bottle";
            NSURL* musicFile = [NSURL fileURLWithPath:[[NSBundle mainBundle]                                                                                                                  pathForResource:@"bebe" ofType:@"wav"]];
            
            
            cry              = [[AVAudioPlayer alloc] initWithContentsOfURL:musicFile  error:nil];
            cry.numberOfLoops = 1;
            cry.volume        = 1;
            [cry play];//Criação do som de Fundo
        }
        else
        {
            bonusNode = [SKSpriteNode spriteNodeWithImageNamed:@"moneyBonus.png"];
            bonusNode.name = @"moneyBonus";
        }
        
        
        
        int pos = CGRectGetMaxX(self.frame);
        bonusNode.position = CGPointMake(arc4random()%pos, 640+moneyNode.size.height/2);
        bonusNode.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:CGSizeMake(enemy.size.width, enemy.size.height)];
        bonusNode.physicsBody.dynamic = NO;
        
        
        bonusNode.physicsBody.categoryBitMask= BottleCategory;
        bonusNode.physicsBody.contactTestBitMask = PlayerCategory;
        bonusNode.physicsBody.collisionBitMask =  PlayerCategory;
        
        bonusNode.zPosition = 3;
        
        [bonusNode setScale:0.3];
        
        
        [self addChild:bonusNode];
        
        SKAction * down = [SKAction moveToY:-moneyNode.size.height duration:2];
        
        [bonusNode runAction:down];
        
        oldTime = time;
    }
    
    
    
    
    
}

-(void) spawnMoney:(float) time;
{
    
    static float oldTime = 0;
    
    if (oldTime == 0) oldTime = time;
    
    
    
    if (time - oldTime > arc4random()%6+2)
    {
        
        moneyNode = [SKSpriteNode spriteNodeWithImageNamed:@"money.png"];
        
        int pos = CGRectGetMaxX(self.frame);
        moneyNode.position = CGPointMake(arc4random()%pos, 640+moneyNode.size.height/2);
        moneyNode.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:CGSizeMake(enemy.size.width, enemy.size.height)];
        moneyNode.physicsBody.dynamic = NO;
        
        
        moneyNode.physicsBody.categoryBitMask= MoneyCategory;
        moneyNode.physicsBody.contactTestBitMask = PlayerCategory;
        moneyNode.physicsBody.collisionBitMask =  PlayerCategory;
        
        moneyNode.zPosition = 3;
        
        [moneyNode setScale:0.3];
        
        
        [self addChild:moneyNode];
        
        SKAction * down = [SKAction moveToY:-moneyNode.size.height duration:4];
        
        [moneyNode runAction:down];
        
        oldTime = time;
    }
    
    
    

    
}



-(void)pan:(UIPanGestureRecognizer *)recognizer
{
    
    BOOL conf = false;
    
    CGPoint translation = [recognizer translationInView:self.view];
    
    if(translation.x)
  
        
        bucket.position = CGPointMake(bucket.position.x + translation.x, bucket.position.y);
        head.position = CGPointMake(bucket.position.x, head.position.y);
    
        [recognizer setTranslation:CGPointZero inView:self.view];
    
  
    
    
    CGPoint vel = [recognizer velocityInView:self.view];
    if (vel.x > 0 && !conf)
    {
        SKAction * right = [SKAction rotateByAngle:0.01 duration:0.7];
        [head runAction:right];
        
       
        
        conf = true;
    }
    else
    {
        SKAction * left = [SKAction rotateByAngle:-0.01 duration:0.7];
        [head runAction:left];
       
       
        
        conf = true;
       
    }
    
    if(recognizer.state == UIGestureRecognizerStateEnded)
    {
        SKAction * back = [SKAction rotateToAngle:0 duration:0.7];
        [head runAction:back];
        conf = false;
    }
}

    
    
    
    



-(void) spawnEnemies: (float) time;
{
    
    
    
    static float oldTime = 0;
    
    if (oldTime == 0) oldTime = time;
    
   
    
    if (time - oldTime > arc4random()%4+1)
    {
        
        if(money>0)
            
        {
            
        diaperTexture = [SKTexture textureWithImageNamed:@"diaper.png"];
        enemy = [SKSpriteNode spriteNodeWithTexture:diaperTexture];
        enemy.name = @"diaper";
        
            
        
            
        }
        else
        {
        shitTexture = [SKTexture textureWithImageNamed:@"shit.png"];
        enemy = [SKSpriteNode spriteNodeWithTexture:shitTexture];
        enemy.name = @"shit";
       
            
        }
        
        if(!money<=0)
        {
            money --;
            NSString * auxStr = [NSString stringWithFormat:@"Money: %d", money];
            moneylabel.text = auxStr;
            
        }
        
        
        int pos = CGRectGetMaxX(self.frame);
        enemy.position = CGPointMake(arc4random()%pos, 640+enemy.size.height/2);
        
        enemy.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:CGSizeMake(CGRectGetWidth(enemy.frame), CGRectGetHeight(enemy.frame))];
        enemy.physicsBody.dynamic = NO;
        
        
        enemy.physicsBody.categoryBitMask= DiaperCategory;
        enemy.physicsBody.contactTestBitMask = PlayerCategory;
        enemy.physicsBody.collisionBitMask =  PlayerCategory;

        
        
        enemy.zPosition = 3;
        
        [enemy setScale:0.3];
        
        
        [self addChild:enemy];
        
        SKAction * down = [SKAction moveToY:-CGRectGetHeight(enemy.frame) duration:4];
        
        [enemy runAction:down];
        
        
        oldTime = time;
        
    }
    

}


-(void)didBeginContact:(SKPhysicsContact *)contact
{
    SKPhysicsBody *firstBody;
    SKPhysicsBody *secondBody;
    
    firstBody = contact.bodyA;
    secondBody = contact.bodyB;
    
    
    if((firstBody.categoryBitMask == PlayerCategory && secondBody.categoryBitMask == MoneyCategory) || (firstBody.categoryBitMask == MoneyCategory && secondBody.categoryBitMask == PlayerCategory))
        
    {
        
        SKLabelNode *DamageLabel = [SKLabelNode labelNodeWithFontNamed:@"Chalkduster"];
        
        SKAction *powerUp = [SKAction playSoundFileNamed:@"Cash.mp3" waitForCompletion:YES];
        [self runAction:powerUp];
        
        
        DamageLabel.verticalAlignmentMode = SKLabelVerticalAlignmentModeCenter;
        
        DamageLabel.text = @"+1$";
        
        DamageLabel.fontSize = 30;
        
        DamageLabel.position = bucket.position;
        
        DamageLabel.alpha = 0;
        
        DamageLabel.zPosition = 6;
        
        money +=1;
        
        NSString * sc1 = [NSString stringWithFormat:@"Money: %d", money];
        
        moneylabel.text = sc1;
        
        DamageLabel.fontColor = [SKColor greenColor];
        
        SKAction *DamageLabelAction = [SKAction fadeInWithDuration:0.2];
        
        [self addChild:DamageLabel];
        
        [DamageLabel runAction:DamageLabelAction];
        
        SKAction * DamageLabelAction2 = [SKAction moveByX:0 y:800 duration:5];
        [DamageLabel runAction:DamageLabelAction2 completion:^
         {
             
             [DamageLabel removeFromParent];
             
             
         }];
        
        
        if(firstBody.node != contactNode && firstBody.node!= enemy)
        {
            [firstBody.node removeFromParent];
        }
        else
        {
            [secondBody.node removeFromParent];
        }
        
    }
    
    else if((firstBody.categoryBitMask == PlayerCategory && secondBody.categoryBitMask == DiaperCategory) || (firstBody.categoryBitMask == DiaperCategory && secondBody.categoryBitMask == PlayerCategory))
        
        
    {
        
        if(firstBody.node != contactNode)
        {
            
            aux  = (SKSpriteNode *)firstBody.node;
            
        }
        
        else
        {
           aux  = (SKSpriteNode *)secondBody.node;
        }
        
        
        if([aux.name isEqual: @"diaper"])
        {
        
            SKLabelNode *DamageLabel = [SKLabelNode labelNodeWithFontNamed:@"Chalkduster"];
            
            SKAction *powerUp = [SKAction playSoundFileNamed:@"powerUp.mp3" waitForCompletion:YES];
            [self runAction:powerUp];
        
            
            DamageLabel.verticalAlignmentMode = SKLabelVerticalAlignmentModeCenter;
            
            DamageLabel.text = @"+1p";
            
            DamageLabel.fontSize = 30;
            
            DamageLabel.position = bucket.position;
            
            DamageLabel.alpha = 0;
            
            DamageLabel.zPosition = 6;
            
            score +=1;
            
            NSString * sc1 = [NSString stringWithFormat:@"Score: %d", score];
            
            scoreLabel.text = sc1;
            
            DamageLabel.fontColor = [SKColor greenColor];
            
            SKAction *DamageLabelAction = [SKAction fadeInWithDuration:0.2];
            
            [self addChild:DamageLabel];
            
            [DamageLabel runAction:DamageLabelAction];
            
            SKAction * DamageLabelAction2 = [SKAction moveByX:0 y:800 duration:5];
            [DamageLabel runAction:DamageLabelAction2 completion:^
             {
                 
                 [DamageLabel removeFromParent];
                 
                 
             }];
            
            
            if(firstBody.node != contactNode && firstBody.node!= moneyNode)
            {
                [firstBody.node removeFromParent];
            }
            else
            {
                [secondBody.node removeFromParent];
            }
        }
        
        
        
        else
        {
            
            lives--;
            
            SKAction *powerUp = [SKAction playSoundFileNamed:@"fart.wav" waitForCompletion:YES];
            [self runAction:powerUp];
            
            if(firstBody.node != contactNode && firstBody.node!= moneyNode)
            {
                [firstBody.node removeFromParent];
            }
            else
            {
                [secondBody.node removeFromParent];
            }

            
            if(lives==2)
            {
                [life3 removeFromParent];
                
            }
            else if (lives==1)
            {
                [life2 removeFromParent];
            }
            else
            {
                [life1 removeFromParent];
                [self gameOver];
                

            }
        }
        
    }
    
    else if((firstBody.categoryBitMask == PlayerCategory && secondBody.categoryBitMask == BottleCategory) || (firstBody.categoryBitMask == BottleCategory && secondBody.categoryBitMask == PlayerCategory))
        
    {
        
        SKLabelNode *DamageLabel = [SKLabelNode labelNodeWithFontNamed:@"Chalkduster"];
        
        if([firstBody.node.name isEqual:@"bottle"] || [secondBody.node.name isEqual:@"bottle"])
        {
            
            
            SKAction *powerUp = [SKAction playSoundFileNamed:@"powerUp.mp3" waitForCompletion:YES];
            [self runAction:powerUp];
            
            DamageLabel.text = @"+15P";
            
            score +=20;
            
            NSString * sc1 = [NSString stringWithFormat:@"Score: %d", score];
            
            scoreLabel.text = sc1;
            
            [cry stop];
            
        }
        
        else if([firstBody.node.name isEqual:@"moneyBonus"] || [secondBody.node.name isEqual:@"moneyBonus"])
        {
            
            SKAction *powerUp = [SKAction playSoundFileNamed:@"Cash.mp3" waitForCompletion:YES];
            [self runAction:powerUp];
            
            DamageLabel.text = @"+8$";
            
            money +=8;
            
            NSString * sc1 = [NSString stringWithFormat:@"Money: %d", money];
            
            moneylabel.text = sc1;
        }
        
        
        DamageLabel.verticalAlignmentMode = SKLabelVerticalAlignmentModeCenter;
        
        
        
        DamageLabel.fontSize = 30;
        
        DamageLabel.position = bucket.position;
        
        DamageLabel.alpha = 0;
        
        DamageLabel.zPosition = 6;
        
        
        DamageLabel.fontColor = [SKColor greenColor];
        
        SKAction *DamageLabelAction = [SKAction fadeInWithDuration:0.2];
        
        [self addChild:DamageLabel];
        
        [DamageLabel runAction:DamageLabelAction];
        
        SKAction * DamageLabelAction2 = [SKAction moveByX:0 y:800 duration:5];
        [DamageLabel runAction:DamageLabelAction2 completion:^
         {
             
             [DamageLabel removeFromParent];
             
             
         }];
        
        
        
        if(firstBody.node != contactNode && firstBody.node!= moneyNode)
        {
            [firstBody.node removeFromParent];
        }
        else
        {
            [secondBody.node removeFromParent];
        }
        
    }





}

-(void)gameOver
{
    
    
    if(!gameOver)
        
    {
        if(score > Records [0])
        {
            
            Records[0] = score;
            
            
            [self writeRecord];
        }
        
        
        GameOver* q = [[GameOver alloc] initWithSize:self.size];
        [q getScore:score getBestScore:Records[0] getMode:4];
        q.scaleMode = SKSceneScaleModeAspectFill;
        SKTransition *transition = [SKTransition fadeWithDuration:1];
        [self.view presentScene: q transition:transition];
        
        gameOver = true;
    }
}

-(void) writeRecord
{
    
    NSNumber * rcd1 = [NSNumber numberWithInt:Records[0]];
    
    [RecordsPersist setObject:rcd1 forKey:@"rcd1S"];
    
    
    NSNumber * rcd2 = [NSNumber numberWithInt:Records[1]];
    
    [RecordsPersist setObject:rcd2 forKey:@"rcd2S"];
    
    
    NSNumber * rcd3 = [NSNumber numberWithInt:Records[2]];
    
    
    [RecordsPersist setObject:rcd3 forKey:@"rcd3S"];
    
    
    
    [RecordsPersist synchronize];
    
    
    
}










@end
