var video;
var myCol;
var socket;

var colThreshold = 5;
var distThreshold = 30;

var blobs = [];
var oscSprava = [];

function setup() {

  socket = io.connect(':3000');

  createCanvas(400, 400);
  pixelDensity(1);
  video = createCapture(VIDEO);
  video.size(400, 400);
  video.hide();
  myCol = color(50, 50, 50);

}

function draw() {
  image(video,0,0);
  blobs = [];
  loadPixels();

  for( var y = 0 ; y < 400 ; y ++ ){
    for ( var x = 0 ; x < 400 ; x ++ ){

      var loc = ( x + y * (400) ) * 4;

      var r = pixels[loc+0];
      var g = pixels[loc+1];
      var b = pixels[loc+2];

      var r2 = myCol[0];
      var g2 = myCol[1];
      var b2 = myCol[2];


      var podoba = dist(r,g,b,r2,g2,b2 );

      if(podoba < colThreshold){

        let found = false;
        for(let i = 0 ; i < blobs.length; i++){
          if(blobs[i].isNear(x,y)){
            blobs[i].add(x,y);
            found = true;
            break;
          }
        }
        if(!found){
          let b = new Blob(x,y);
          blobs.push(b);
        }
      }
    }
  }
  updatePixels();
  for(let i = 0 ; i < blobs.length; i++){
    blobs[i].show();
    socket.emit('kamera',blobs[i].send());
  }
}

class Blob{

  constructor(x,y){
    this.minx = x;
    this.miny = y;
    this.maxx = x;
    this.maxy = y;

  }

  isNear(x,y){
    let cx = (this.minx + this.maxx) / 2;
    let cy = (this.miny + this.maxy) / 2;

    let d = dist(cx,cy,x,y);
    if (d < distThreshold ){
      return true;
    }
    else return false;
  }
  add(x,y){
    this.minx = min(this.minx,x);
    this.miny = min(this.miny,y);
    this.maxx = max(this.maxx,x);
    this.maxy = max(this.maxy,y);
  }
  show(){
    stroke(0);
    fill(255);
    strokeWeight(2);
    rectMode(CORNERS);
    rect(this.minx, this.miny, this.maxx,this.maxy);
  }
  send(){
    let x = dist(this.minx,this.miny,this.maxx,this.maxy, );
    let cx = (this.minx + this.maxx) / 2;
    let cy = (this.miny + this.maxy) / 2;

    let xx = map(cx,0,300,0,1);
    let yy = map(cy,0,300,0,1);
    let sx = map(x,0,100,0,1);

    return [xx,yy,sx];
  }
}

function mousePressed(){
  var loc = ( mouseX + mouseY * (400)  ) * 4;
  myCol = [ pixels[loc], pixels[loc+1],pixels[loc+2]];
  print("Farba " + myCol + " X Y " + mouseX, mouseY);
}

function doubleClicked() {
  myCol = [];
  print('dvojkliiik');
}
