//
//  MyScene.m
//  SpriteKit_iOS_Game
//
//  Created by pgAgent on 22/09/2014.
//  Copyright (c) 2014 RJM Programming. All rights reserved.
//

#import "MyScene.h"

@implementation MyScene

-(id)initWithSize:(CGSize)size {
    if (self = [super initWithSize:size]) {
        
        
        /* Setup your scene here */
        
        self.backgroundColor = [SKColor colorWithRed:0.55 green:0.15 blue:0.03 alpha:1.0];
        
        SKLabelNode *myLabel = [SKLabelNode labelNodeWithFontNamed:@"Chalkduster"];
        
        myLabel.text = @"Hello, World ... Welcome to SpriteKit Game!";
        myLabel.fontSize = 30;
        myLabel.position = CGPointMake(CGRectGetMidX(self.frame),
                                       CGRectGetMidY(self.frame));
        
        [self addChild:myLabel];
    }
    return self;
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
 
    int r=0, rrx=0, rry=0, kk = 0;
    char *ilist[8] = {"Spaceship", "onestar", "twostar", "threestar", "fourstar", "fivestar", "sixstar", "sevenstar"};
    NSMutableArray *randArray = [NSMutableArray new];
    NSMutableArray *bodies = [NSMutableArray array];
    SKTextureAtlas* atlas = [SKTextureAtlas atlasNamed:@"SpriteKit_iOS_Game"];
    for (int k = 0; k < 8; k++) {
        r = arc4random() % 8;
        rrx = (r - arc4random() % 8);
        rry = (r - arc4random() % 8);
        if ([randArray containsObject:[NSString stringWithFormat:@"%s", ilist[r]]]){
            k--;
        } else {
            if (r == 0) kk = k;
            NSString *textureName = [NSString stringWithFormat:@"%s", ilist[r]];
            SKTexture* texture = [atlas textureNamed:textureName]; //]nlist[r]];
            [bodies addObject:[SKSpriteNode spriteNodeWithTexture:texture]];
            [randArray addObject:[NSString stringWithFormat:@"%s", ilist[r]]];
        }
    }
    r = arc4random() % 8;
    rrx = (r - arc4random() % 8);
    rry = (r - arc4random() % 8);
    
    
    /* Called when a touch begins */
    
    for (UITouch *touch in touches) {
        CGPoint location = [touch locationInNode:self];
        
        SKSpriteNode *sprite = bodies[r]; //[SKSpriteNode spriteNodeWithImageNamed:randArray[r]];
        
        sprite.position = location;
        sprite.scale = 0.5;
        
        SKAction *action;
        if (r == kk) {
            sprite.scale = 0.5;
            action = [SKAction rotateByAngle:-M_PI duration:1];
        } else {
            CGVector negDelta = CGVectorMake(rrx,rry);
            action = [SKAction moveBy: negDelta duration: 1];
        }
        
        [sprite runAction:[SKAction repeatActionForever:action]];
        
        [self addChild:sprite];
    }
}

-(void)update:(CFTimeInterval)currentTime {
    /* Called before each frame is rendered */
}

@end
