var data;
var socket;
var maxLopty = 5;
var lopty = [];

var alpha,beta,gamma;
var col = 50;

function setup() {
  createCanvas(windowWidth, windowHeight);
  noStroke();
  background(50);
  fill(255);

  socket = io.connect(':3000');
  socket.on('ball',newDrawing);

  var options = {
    preventDefault: true
  };

  var hammer = new Hammer(document.body, options);
  hammer.get('swipe').set({
    direction: Hammer.DIRECTION_ALL
  });
}

function draw() {
  background(col);
  for(var i = 0; i < lopty.length ; i++){
    lopty[i].update();
    lopty[i].vel.x +=  gamma * 0.01;
    lopty[i].vel.y +=  beta * 0.01;
  }
}

function singleTap(){
  for(var i = 0; i < lopty.length ; i++){
    if(lopty[i].clicked(mouseX,mouseY)){
      lopty.splice(i,1);
      return;
    }
  }
  if(lopty.length < maxLopty)lopty.push(new Ball());
}

function swiped(event) {
  console.log("swiped");
  for(var i = 0; i < lopty.length ; i++){
    lopty[i].vel.x += random(20)*event.velocityX;
    lopty[i].vel.y += random(20)*event.velocityY;
  }
}

window.addEventListener('deviceorientation', function(e) {
  alpha = e.alpha;
  beta = e.beta;
  gamma = e.gamma;
 });

function Ball(){

  this.pos = createVector(windowWidth/2,windowHeight/2);
  this.vel = createVector(random(-40,40),random(-40,40));
  this.diameter = random(windowWidth/30,windowWidth/3);
  this.col = color(random(255),random(255),random(255));

  this.update = function(){
    fill(this.col);
    ellipse(this.pos.x, this.pos.y, this.diameter, this.diameter);

    this.pos.add(this.vel);

    	if(this.pos.x >= windowWidth){
        this.vel.x  = -abs(this.vel.x);
        this.send();
      }
      else if (this.pos.x  <= 0 ){
        this.vel.x = abs(this.vel.x);
        this.send();
    	}

      if(this.pos.y >= windowHeight){
        this.vel.y = -abs(this.vel.y);
        this.send();
      }
      else if (this.pos.y  <= 0 ){
        this.vel.y = abs(this.vel.y);
        this.send();
    	}

    this.vel.mult(0.993);
  };

  this.send = function(){
    var x =  map(this.pos.x,0,windowWidth,0,1);
    var y = map(this.pos.y,0,windowHeight,0,1);
    var d = map(this.diameter,0,(windowWidth/3),0,1);
    var uhol = vypocetUhlu(this.pos.x,this.pos.y)
    socket.emit('ballPos', [x,y,d,uhol]);
  };

  this.clicked = function(x,y){
    var d = dist(x,y,this.pos.x,this.pos.y);
    if(d <= this.diameter)return true;
    else return false;
  }
  this.dragged = function(){
    var d = dist(mouseX,mouseY,this.pos.x,this.pos.y);
    if(d < this.diameter){
      this.vel.mult(0);
      this.pos.x = mouseX;
      this.pos.y = mouseY;
    }
  }
}

function touchStarted(){
  col = color(255,0,255);
}
function touchEnded(){
  col = 50;
}
function vypocetUhlu(x,y){
  var angle = atan2((windowHeight/2)-y,(windowWidth/2)-x);
  pop();
  return map(((degrees(angle)+270)%360),0,360,1,0);

}
