//
//  ViewController.m
//  SimpleGLESgame
//
//  Created by Vedran Murgić on 24.01.2014..
//  Copyright (c) 2014. Vedran Murgić. All rights reserved.
//

#import "ViewController.h"
#import "Sprite.h"

typedef struct{
    GLKVector3 positionCoordinates;
    GLKVector2 textureCoordinates;
} VertexData;

#define VISINA 1536
#define SIRINA 2048

#define stranicaA 200
#define stranicaB 200
float stranicaAA =  100.0f;
float stranicaBB =  100.0f;

float boja = 255.0;
int smjer = 1;
int smjerStranicaA = 1;

int att = 0;
int med = 0;
int blink = 0;

NSTimeInterval timeInMiliseconds;
BOOL crtajBlink = NO;

VertexData vertices[] = {
    //mozak
    {{0.0f, 0.0f, -3.0f}, {0.0f, 0.0f}},
    {{stranicaB, 0.0f, -3.0f}, {1.0f, 0.0f}},
    {{0.0f, stranicaA, -3.0f}, {0.0f, 1.0f}},
    {{0.0f, stranicaA, -3.0f}, {0.0f, 1.0f}},
    {{stranicaB, 0.0f, -3.0f}, {1.0f, 0.0f}},
    {{stranicaB, stranicaA, -3.0f}, {1.0f, 1.0f}},
    
    //pozadina
    {{0.0f, 0.0f, -0.1f}, {0.0f, 0.0f}},
    {{SIRINA, 0.0f, -0.1f}, {1.0f, 0.0f}},
    {{0.0f, VISINA, -0.1f}, {0.0f, 1.0f}},
    {{SIRINA, 0.0f, -0.1f}, {1.0f, 0.0f}},
    {{0.0f, VISINA, -0.1f}, {0.0f, 1.0f}},
    {{SIRINA, VISINA, -0.1f}, {1.0f, 1.0f}},
    
    //att
    {{0.0f, 0.0f, -3.0f}, {0.0f, 0.0f}},
    {{stranicaA, 0.0f, -3.0f}, {1.0f, 0.0f}},
    {{0.0f, stranicaA, -3.0f}, {0.0f, 1.0f}},
    {{0.0f, stranicaA, -3.0f}, {0.0f, 1.0f}},
    {{stranicaA, 0.0f, -3.0f}, {1.0f, 0.0f}},
    {{stranicaA, stranicaA, -3.0f}, {1.0f, 1.0f}},
    
    //med
    {{0.0f, 0.0f, -3.0f}, {0.0f, 0.0f}},
    {{0.0f, 0.0f, -3.0f}, {1.0f, 0.0f}},
    {{0.0f, stranicaA, -3.0f}, {0.0f, 1.0f}},
    {{0.0f, stranicaA, -3.0f}, {0.0f, 1.0f}},
    {{stranicaB, 0.0f, -3.0f}, {1.0f, 0.0f}},
    {{stranicaB, stranicaA, -3.0f}, {1.0f, 1.0f}}
};

@interface ViewController ()

@property (nonatomic, strong) EAGLContext *context;
@property (nonatomic, strong) GLKBaseEffect *baseEffect;
@property (nonatomic, strong) Sprite *mozak;
@property (nonatomic, strong) Sprite *back;
@property (nonatomic, strong) Sprite *attBack;
@property (nonatomic, strong) Sprite *att;
@property (nonatomic, strong) Sprite *med;
@property (nonatomic, strong) Sprite *medBack;
@property (nonatomic, strong) Sprite *blink;

@end

@implementation ViewController{
    GLuint _vertexBufferID;
    GLuint _depthRenderbuffer;
}

- (void)viewDidLoad
{
    
    [super viewDidLoad];
    
    if([[TGAccessoryManager sharedTGAccessoryManager] accessory] != nil){
        [[TGAccessoryManager sharedTGAccessoryManager] startStream];
        NSLog(@"startaoStream");
        NSLog(@"TGAccessory version: %d", [[TGAccessoryManager sharedTGAccessoryManager] getVersion]);

    }
    
    NSLog(@"Ide li stream: %hhd", [[TGAccessoryManager sharedTGAccessoryManager] connected]);
	
    NSLog(@"sad sam u viewDidLoad");
    self.context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2];
    
    GLKView *view = (GLKView *)self.view;
    view.context = self.context;
    view.drawableDepthFormat = GLKViewDrawableDepthFormat24;

    [EAGLContext setCurrentContext:self.context];
    
    self.baseEffect = [[GLKBaseEffect alloc] init];
    self.baseEffect.useConstantColor = YES;
    //self.baseEffect.constantColor = GLKVector4Make(boja/255.0f, 0.0f, 0.0f, 1.0f);
    
    //iPad rezolucija --> 2048pxx1536px
    self.baseEffect.transform.projectionMatrix = GLKMatrix4MakeOrtho(0, SIRINA, 0, VISINA, 10.0f, -10.0f);
    
    glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
    
    glGenBuffers(1, &_vertexBufferID);
    glBindBuffer(GL_ARRAY_BUFFER, _vertexBufferID);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_DYNAMIC_DRAW);
    glEnableVertexAttribArray(GLKVertexAttribPosition);
    glVertexAttribPointer(GLKVertexAttribPosition, 3, GL_FLOAT, GL_FALSE, sizeof(VertexData), offsetof(VertexData, positionCoordinates));
    
    glEnableVertexAttribArray(GLKVertexAttribTexCoord0);
    glVertexAttribPointer(GLKVertexAttribTexCoord0, 2, GL_FLOAT, GL_FALSE, sizeof(VertexData), (GLvoid *) offsetof(VertexData, textureCoordinates));
    
    glEnable(GL_BLEND);
    //glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_LEQUAL);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    
    UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(upravljajDodirom:)];
    [self.view addGestureRecognizer:gestureRecognizer];
    
    CGImageRef imageReference = [[UIImage imageNamed:@"mozak.png"] CGImage];
    
    GLKTextureInfo *textureInfo = [GLKTextureLoader textureWithCGImage:imageReference
                                                               options:[NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:GLKTextureLoaderOriginBottomLeft]
                                                                 error:NULL];
    //pažnja
    CGImageRef imageReferencePaznja = [[UIImage imageNamed:@"paznja.jpg"] CGImage];
    
    GLKTextureInfo *textureInfoPaznja = [GLKTextureLoader textureWithCGImage:imageReferencePaznja
                                                                   options:[NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:GLKTextureLoaderOriginBottomLeft]
                                                                     error:NULL];
    
    //meditacija
    CGImageRef textureReferenceMeditacija = [[UIImage imageNamed:@"meditacija.jpg"] CGImage];
    
    GLKTextureInfo *textureInfoMeditacija = [GLKTextureLoader textureWithCGImage:textureReferenceMeditacija
                                                                     options:[NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:GLKTextureLoaderOriginBottomLeft]
                                                                       error:NULL];
    
    
    //blink
    CGImageRef textureReferenceBlink = [[UIImage imageNamed:@"oko.jpg"] CGImage];
    
    GLKTextureInfo *textureInfoBlink = [GLKTextureLoader textureWithCGImage:textureReferenceBlink
                                                                         options:[NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:GLKTextureLoaderOriginBottomLeft]
                                                                           error:NULL];
    
    //background
    CGImageRef imageReferenceBack = [[UIImage imageNamed:@"backSinappsa.jpg"] CGImage];
    
    GLKTextureInfo *textureInfoBack = [GLKTextureLoader textureWithCGImage:imageReferenceBack
                                                               options:[NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:GLKTextureLoaderOriginBottomLeft]
                                                                 error:NULL];
    self.back =[[Sprite alloc] initWithEffect:self.baseEffect];
    self.back.textureInfo = textureInfoBack;
    self.back.position = GLKVector2Make(0, 0);
    
    self.mozak = [[Sprite alloc] initWithEffect:self.baseEffect];
    self.mozak.textureInfo = textureInfo;
    self.mozak.position = GLKVector2Make(300,200);
    
    self.att =[[Sprite alloc] initWithEffect:self.baseEffect];
    self.att.textureInfo = textureInfoPaznja;
    self.att.position = GLKVector2Make(0, 200);
    
    self.attBack =[[Sprite alloc] initWithEffect:self.baseEffect];
    self.attBack.textureInfo = textureInfoPaznja;
    self.attBack.position = GLKVector2Make(0, 200);


    self.medBack =[[Sprite alloc] initWithEffect:self.baseEffect];
    self.medBack.textureInfo = textureInfoMeditacija;
    self.medBack.position = GLKVector2Make(200, 0);
    
    self.med =[[Sprite alloc] initWithEffect:self.baseEffect];
    self.med.textureInfo = textureInfoMeditacija;
    self.med.position = GLKVector2Make(200, 0);
    
    self.blink =[[Sprite alloc] initWithEffect:self.baseEffect];
    self.blink.textureInfo = textureInfoBlink;
    self.blink.position = GLKVector2Make(0, 0);
    
    //self.mozak.rotation = 90;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)viewWillDisappear:(BOOL)animated{
    NSLog(@"Nestajem");
    if([[TGAccessoryManager sharedTGAccessoryManager] connected]) [[TGAccessoryManager sharedTGAccessoryManager] startStream];
}

#pragma mark - GLKView delegate methods

- (void) glkView:(GLKView *)view drawInRect:(CGRect)rect{
    //NSLog(@"sad sam u glkView %f", boja);
    
    if([[TGAccessoryManager sharedTGAccessoryManager] accessory] == nil){
        //NSLog(@"Nije spojen");
    }
    else {
        //NSLog(@"SPOJEN JE!!!!!!!!!!");
        //att = eSenseValues.meditation;
        //NSLog(@"att: %d", att);
    }
    
        
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    
    float attV = ((float)att / 100) * (VISINA - stranicaB);
    float medS = ((float)med / 100) * (SIRINA - stranicaB);
    float attTex = (float)attV / (float)(VISINA - stranicaB);
    float medTex = (float)medS / (float)(SIRINA - stranicaB);
    
    float mozakXtrenutno = self.mozak.position.x;
    float mozakYtrenutno = self.mozak.position.y;
    float mxCilj = (stranicaB / 2) + (medTex * (float)(SIRINA - stranicaB));
    float myCilj = (stranicaB / 2) + (attTex * (float)(VISINA - stranicaB));
    float korakX = (mxCilj - mozakXtrenutno) / 10.0f;
    float korakY = (myCilj - mozakYtrenutno) / 10.0f;
    float mx = mozakXtrenutno + korakX;
    float my = mozakYtrenutno + korakY;
    
    //NSLog(@"mozakTrenutno: %f %f",mozakXtrenutno, mozakYtrenutno);
    //NSLog(@"mx: %f   my: %f", mx, my);
    self.mozak.position = GLKVector2Make(mx, my);
    
    if(([[NSDate date] timeIntervalSince1970] - timeInMiliseconds) < 1){
        crtajBlink = YES;
        //NSLog(@"crtamBlink: %f", [[NSDate date] timeIntervalSince1970] - timeInMiliseconds);
    }else{
        crtajBlink = NO;
        //NSLog(@"NE crtamBlink: %f", [[NSDate date] timeIntervalSince1970] - timeInMiliseconds);
    }
    
    [self.back render:@"back"];
    [self.mozak render:@"mozak"];
    [self.att render:@"attBack"];
    [self.med render:@"medBack"];
    [self.att render:@"att"];
    [self.med render:@"med"];
    if(crtajBlink == YES){
        [self.blink render:@"blink1"];
    }else{
        [self.blink render:@"blink0"];
    }
    
    VertexData mozak[] = {
        //mozak
        {{0.0f, 0.0f, -3.0f}, {0.0f, 0.0f}},
        {{stranicaB, 0.0f, -3.0f}, {1.0f, 0.0f}},
        {{0.0f, stranicaA, -3.0f}, {0.0f, 1.0f}},
        {{0.0f, stranicaA, -3.0f}, {0.0f, 1.0f}},
        {{stranicaB, 0.0f, -3.0f}, {1.0f, 0.0f}},
        {{stranicaB, stranicaA, -3.0f}, {1.0f, 1.0f}},
        
        //pozadina
        {{0.0f, 0.0f, -0.1f}, {0.0f, 0.0f}},
        {{SIRINA, 0.0f, -0.1f}, {1.0f, 0.0f}},
        {{0.0f, VISINA, -0.1f}, {0.0f, 1.0f}},
        {{SIRINA, 0.0f, -0.1f}, {1.0f, 0.0f}},
        {{0.0f, VISINA, -0.1f}, {0.0f, 1.0f}},
        {{SIRINA, VISINA, -0.1f}, {1.0f, 1.0f}},
        
        //att
        {{0.0f, 0.0f, -3.0f}, {0.0f, 0.0f}},
        {{stranicaA, 0.0f, -3.0f}, {1.0f, 0.0f}},
        {{0.0f, attV, -3.0f}, {0.0f, attTex}},
        {{0.0f, attV, -3.0f}, {0.0f, attTex}},
        {{stranicaA, 0.0f, -3.0f}, {1.0f, 0.0f}},
        {{stranicaA, attV, -3.0f}, {1.0f, attTex}},
        
        //med
        {{0.0f, 0.0f, -3.0f}, {0.0f, 0.0f}},
        {{0.0f, stranicaA, -3.0f}, {0.0f, 1.0f}},
        {{medS, 0.0f, -3.0f}, {medTex, 0.0f}},
        {{0.0f, stranicaA, -3.0f}, {0.0f, 1.0f}},
        {{medS, 0.0f, -3.0f}, {medTex, 0.0f}},
        {{medS, stranicaA, -3.0f}, {medTex, 1.0f}},
        
        //attBack
        {{0.0f, 0.0f, -3.0f}, {0.0f, 0.0f}},
        {{stranicaA, 0.0f, -3.0f}, {1.0f, 0.0f}},
        {{0.0f, VISINA - stranicaB, -3.0f}, {0.0f, 1.0f}},
        {{0.0f, VISINA - stranicaB, -3.0f}, {0.0f, 1.0f}},
        {{stranicaA, 0.0f, -3.0f}, {1.0f, 0.0f}},
        {{stranicaA, VISINA - stranicaB, -3.0f}, {1.0f, 1.0f}},
        
        //medBack
        {{0.0f, 0.0f, -3.0f}, {0.0f, 0.0f}},
        {{0.0f, stranicaA, -3.0f}, {0.0f, 1.0f}},
        {{SIRINA - stranicaB, 0.0f, -3.0f}, {1.0f, 0.0f}},
        {{0.0f, stranicaA, -3.0f}, {0.0f, 1.0f}},
        {{SIRINA - stranicaB, 0.0f, -3.0f}, {1.0f, 0.0f}},
        {{SIRINA - stranicaB, stranicaA, -3.0f}, {1.0f, 1.0f}},
        
        //blink
        {{0.0f, 0.0f, -3.0f}, {0.0f, 0.0f}},
        {{0.0f, stranicaA, -3.0f}, {0.0f, 1.0f}},
        {{stranicaB, 0.0f, -3.0f}, {1.0f, 0.0f}},
        {{0.0f, stranicaA, -3.0f}, {0.0f, 1.0f}},
        {{stranicaB, 0.0f, -3.0f}, {1.0f, 0.0f}},
        {{stranicaB, stranicaA, -3.0f}, {1.0f, 1.0f}}
    };
    
    //NSLog(@"attV: %d %f", att, attV);
    
    
    //boja
    if((boja + 5.0) > 255){
        smjer = 0;
    }else if((boja - 5.0) < 0){
        smjer = 1;
    }
    if(smjer == 1){
        boja += 5.0;
    }else{
        boja -= 5.0;
    }
    
    //promjena visine
    if((stranicaAA + 15.0) > VISINA){
        smjerStranicaA = 0;
    }else if((stranicaAA - 15.0) < 0){
        smjerStranicaA = 1;
    }
    if(smjerStranicaA == 1){
        stranicaAA += 15.0;
    }else{
        stranicaAA -= 15.0;
    }
    
    
    
    glBufferData(GL_ARRAY_BUFFER, sizeof(mozak), mozak, GL_DYNAMIC_DRAW);
}

- (void) update{
    //NSLog(@"sad sam u update");
    [self.back update];
    [self.mozak update];
    
}

#pragma mark - ns metode
- (void)dataReceived:(NSDictionary *)data {
    /*NSLog(@"Data received!");
    NSLog(@"Raw: %d", [[data valueForKey:@"raw"] intValue]);
    NSLog(@"Attention: %d", [[data valueForKey:@"eSenseAttention"] intValue]);*/
    //NSLog(@"Čisti ulaz: %@", data);
    if([data valueForKey:@"eSenseAttention"]){
        att = [[data valueForKey:@"eSenseAttention"] intValue];
        med =[[data valueForKey:@"eSenseMeditation"] intValue];
    }
    if([data valueForKey:@"blinkStrength"]){
        blinkStrength = [[data valueForKey:@"blinkStrength"] intValue];
        //NSLog(@"Blinkaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
        timeInMiliseconds = [[NSDate date] timeIntervalSince1970];
        //NSLog(@"milis: %f", timeInMiliseconds);
    }
    //NSLog(@"Blink: %d", blinkStrength);
}

- (void)accessoryDidConnect:(EAAccessory *)accessory {
    NSLog(@"%@ was connected to this device.", [accessory name]);
    UIAlertView * a = [[UIAlertView alloc] initWithTitle:@"MindWave se spojio!"
                                                 message:[NSString stringWithFormat:@"ThinkGear dodatak %@ se spojio na uređaj.", [accessory name]]
                                                delegate:nil
                                       cancelButtonTitle:@"OK"
                                       otherButtonTitles:nil];
    [a show];

    [[TGAccessoryManager sharedTGAccessoryManager] startStream];
}
- (void)accessoryDidDisconnect {
    NSLog(@"An accessory was disconnected.");
    UIAlertView * a = [[UIAlertView alloc] initWithTitle:@"MindWave se odspojio"
                                                 message:[NSString stringWithFormat:@"ThinkGear dodatak se odspojio."]
                                                delegate:nil
                                       cancelButtonTitle:@"OK"
                                       otherButtonTitles:nil];
    [a show];
}

#pragma mark - dodir
-(void) upravljajDodirom:(UITapGestureRecognizer *)gestureRecognizer{
    NSLog(@"dodir");
    if([[TGAccessoryManager sharedTGAccessoryManager] accessory] == nil){
        timeInMiliseconds = [[NSDate date] timeIntervalSince1970];
    }
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    //CGPoint tocka = [[touches anyObject] locationInView:self.view];
    //NSLog(@"x: %f  y: %f", tocka.x, tocka.y);
    /*if([[TGAccessoryManager sharedTGAccessoryManager] accessory] == nil){
        att = 100.0 - (tocka.y / 760.5) * 100;
        med = (tocka.x / 1022.5) * 100;
    }*/
}

-(void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
    CGPoint tocka = [[touches anyObject] locationInView:self.view];
    //NSLog(@"x: %f  y: %f", tocka.x, tocka.y);
    if([[TGAccessoryManager sharedTGAccessoryManager] accessory] == nil){
        att = 100.0 - (tocka.y / 760.5) * 100;
        med = (tocka.x / 1022.5) * 100;
    }
}

@end
