/*--------------------Graficas----------------------*/
var downloadFile = function (filename, text) {
  var element = document.createElement('a');
  //element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
  element.href = text;
  element.setAttribute('download', filename);

  element.style.display = 'none';
  document.body.appendChild(element);

  element.click();

  document.body.removeChild(element);
};

var loadData = function(data,cuts){//recibe un arreglo con los datos

  var cortes = [];

  for(var i = 0; i < cuts; i++){
      cortes[i] = i;
  }

  //alert("data : " + data);
  //alert("cortes : " + cortes);

  var datos_grafico = {
      labels : cortes,//cantidad de cortes
      datasets : [
      {
          label: "Densidad cerebral por cortes",
          fill: true,
          lineTension: 0.1,
          backgroundColor: "rgba(131,176,193,0.4)",
          borderColor: "rgba(17,37,58,1)",
          borderCapStyle: 'butt',
          borderDash: [],
          borderDashOffset: 0.0,
          borderJoinStyle: 'miter',
          borderWidth : 1,
          pointBorderColor: "rgba(0,0,0,1)",//"rgba(75,192,192,1)",
          pointBackgroundColor: "#fff",
          pointBorderWidth: 0.5,
          pointHoverRadius: 5,
          pointHoverBackgroundColor: "rgba(75,192,192,1)",
          pointHoverBorderColor: "rgba(220,220,220,1)",
          pointHoverBorderWidth: 1,
          pointRadius: 1,
          pointHitRadius: 5,
          pointHoverBorderColor : "rgba(0,0,0,1)",
          data : data //este se reempaza por los datos obtenidos en los cortes
      }
      ]
  }
  createGraphic(datos_grafico);
}

var removeGraphicSpace = function () {
  var padre = document.querySelector("#crearGrafico");
  var fc = padre.firstChild;
  while( fc ) {
      padre.removeChild( fc );
      fc = padre.firstChild;
  }
}

var createGraphicSpace = function () {
  removeGraphicSpace();

  var padre = document.querySelector("#crearGrafico");

  var primero = document.createElement("div");
  primero.className = "row";

  var segundo = document.createElement("div");
  segundo.id = "grafico";

  primero.appendChild(segundo);

  var tercero = document.createElement("canvas");
  tercero.id = "myChart";

  segundo.appendChild(tercero);

  padre.appendChild(primero);
}

var createGraphic = function (datos_grafico){
  //console.log("grafico : " , grafico);
  //grafico.className = "";

  createGraphicSpace(); // crea los divs
  var grafico = document.querySelector("#myChart");

  var myNewChart = new Chart(grafico , {
    type: "line",
    data: datos_grafico,
  });
  download.className = download.className.replace("hidden","");//le quitamos el hidden
}

var readFile = function(){
  if(id === undefined){
    //console.log("id undefined");
    return;
  }
  jQuery.get('densities/partial_density'+id+'.txt', function(txt) {
  //jQuery.get('densities/partial_density.txt',function(txt){
    var partial_sum = []
    partial_sum = txt.replace(/\s/g,"");//quita todos los espacios
    var array = partial_sum.split(',');
    var array2 = []

    for(var i = 1; i < array.length; i++){
      array2[i-1] = array[i];
    }

    loadData(array2,array[0]);
  });

}

var getCookieId = function(){
  var cookie = document.cookie;
  var splitted = cookie.split("id=");
  //console.log("splitted[0] : ", splitted[0]);
  //console.log("splitted[1] : ", splitted[1]);
  return splitted[1];
}

/*----------------Sockets------------------*/

var io = require('socket.io-client')(),
    send = document.querySelector("#btn_index"),
    download = document.querySelector("#downloadForm"),
    loader = document.querySelector("#btn-loader"),
    id;

if ( document.URL.contains("/grafica") ) {
  id = getCookieId();
  readFile();
  console.log("id adentro: ", id);
}

window.onbeforeunload = function confirmExit(){
  io.emit('delete data', "../../data/density"+id+".txt"+" public/densities/partial_density"+id+".txt");
  //return "¿Está seguro que quiere abandonar la página?";
};

io.on('serverReady', function(data) {
  //console.log("io.on serverReady");
  io.emit('clientReady', {
    path: window.location.pathname,
    data: 'El cliente está listo.',
    cookieID: getCookieId()
  });
});

send.addEventListener("click", function(e){
    download.className = download.className + " hidden";
    loader.className = loader.className.replace(" hidden","");
    removeGraphicSpace();
    io.emit('delete data', "../../data/density"+id+".txt"+" public/densities/partial_density"+id+".txt");
});

download.addEventListener("click", function (){
  dir = '../densities/partial_density'+id+'.txt';
  downloadFile("datos_grafica",dir);
});
