var colors;
var grains = [];
var socket;
var angle ;

function setup() {
  createCanvas(displayWidth, displayHeight);
  background(200);
  pixelDensity(1);
  socket = io.connect(':3000');
}

function draw() {
  background(200);
  beginShape();
  fill(255);
  for (var i = 0; i < touches.length; i++) {
    vertex(touches[i].x, touches[i].y);
  }
  endShape(CLOSE);
}

function touchMoved(event) {
  var touch = event.changedTouches;
  var dlzka = touch.length;
  var x, y , mapX, mapY;
  var uhol;
  let i = 0;
  for(i; i < dlzka; i ++){

    x = (touch[i]).clientX;
    y = (touch[i]).clientY;
    mapX = map(x,0,displayWidth,0,1);
    mapY = map(y,0,displayHeight,0,1);
    uhol = vypocetUhlu(x,y);
    if(i == 0)socket.emit('multitouchLast',[mapX, mapY,uhol]);
    socket.emit('multitouch',[mapX, mapY,uhol]);
  }
  return false;
}

function vypocetUhlu(x,y){
  //vypocet uhlu dotyku od stredu a prepocet 0-1 proti hodinovym rucickam pre PD
  translate(displayWidth/2, displayHeight/2);
  var angle = atan2((displayHeight/2)-y,(displayWidth/2)-x);
  return map(((degrees(angle)+270)%360),0,360,1,0);
}

function grain(r){
  this.x = 0;
  this.y = 0;
  this.r = r;
  this.col = [random(255),random(255),random(255)];
  print(this.x,this.y);grains.push(new grain(random(10,100)));
  this.show = function(x,y){
    this.x = x ;
    this.y = y;
    push();
    fill(this.col);
    ellipse(x,y,this.r,this.r);
    pop();
  }
}
