@Html.Partial("admin/_header.cshtml")

<style>
  .axis path,
  .axis line {
    fill: none;
    stroke: grey;
    stroke-width: 1;
    shape-rendering: crispEdges;
  }

  .axis path,
  .axis line {
    fill: none;
    stroke: black;
    opacity: 0.2;
  }
</style>

<!-- ============================================================== -->
<!-- pageheader  -->
<!-- ============================================================== -->
<div class="row">
  <div class="col-xl-12 col-lg-12 col-md-12 col-sm-12 col-12">
    <div class="page-header">
      <h2 class="pageheader-title">Process info</h2>
    </div>
  </div>
</div>

<div class="row">
  Name: @ViewBag.Process.Value.Name
</div>
<div class="row">
  Creation date: @ViewBag.Process.Value.CreationDate
</div>

<div class="row">
  <a href="http://localhost:8888/EvaluationAnalytics/@Uri.EscapeUriString(ViewBag.Process.Value.Name)/0" target="_blank" class="btn btn-primary">
    Frame found CSV
  </a>
  <a href="http://localhost:8888/EvaluationAnalytics/@Uri.EscapeUriString(ViewBag.Process.Value.Name)/2" target="_blank" class="btn btn-primary">
    Shot found CSV
  </a>
  <a href="http://localhost:8888/EvaluationAnalytics/@Uri.EscapeUriString(ViewBag.Process.Value.Name)/1" target="_blank" class="btn btn-primary">
    Video found CSV
  </a>
</div>

<div class="row">
  <a href="http://localhost:8888/EvaluationAnalytics/@Uri.EscapeUriString(ViewBag.Process.Value.Name)/detail/0" target="_blank" class="btn btn-primary">
    Frame detail search CSV
  </a>
  <a href="http://localhost:8888/EvaluationAnalytics/@Uri.EscapeUriString(ViewBag.Process.Value.Name)/detail/1" target="_blank" class="btn btn-primary">
    Shot detail search CSV
  </a>
  <a href="http://localhost:8888/EvaluationAnalytics/@Uri.EscapeUriString(ViewBag.Process.Value.Name)/detail/2" target="_blank" class="btn btn-primary">
    Video detail search CSV
  </a>
</div>

<!-- Load d3.js -->
<script src="https://d3js.org/d3.v4.js"></script>

<!-- Create a div where the graph will take place -->
<h5 class="card-header">Exact image found</h5>
<div class="row">
  <div id="rf_0FOdiv"></div>
  <div class="col-xl-6 col-lg-6 col-md-6 col-sm-12 col-12">
    <p id="rf_0FOp"></p>
  </div>
</div>
<h5 class="card-header">Frame from shot found</h5>
<div class="row">
  <div id="rf_2FOdiv"></div>
  <div class="col-xl-6 col-lg-6 col-md-6 col-sm-12 col-12">
    <p id="rf_2FOp"></p>
  </div>
</div>
<h5 class="card-header">Frame from target video found</h5>
<div class="row">
  <div id="rf_1FOdiv"></div>
  <div class="col-xl-6 col-lg-6 col-md-6 col-sm-12 col-12">
    <p id="rf_1FOp"></p>
  </div>
</div>
<h5 class="card-header">Average target rank</h5>
<div class="row">
  <div id="rf_3FOdiv"></div>
  <div class="col-xl-6 col-lg-6 col-md-6 col-sm-12 col-12">
    <p id="rf_3FOp"></p>
  </div>
</div>

<script>
  const numOfSheets = 4;
  const maximums = [1, 1, 1, -1];

  // set the dimensions and margins of the graph
  var margin = { top: 10, right: 30, bottom: 30, left: 60 },
    width = 460 - margin.left - margin.right,
    height = 400 - margin.top - margin.bottom;

  var colorRange = ['#e41a1c', '#377eb8', '#4daf4a', '#984ea3', '#ff7f00', '#ffff33', '#a65628', '#f781bf', '#999999'];
  for (var i = colorRange.length; i < @ViewBag.ClassesCount; i++) {
    colorRange.push(getRandomColor());
  }

  var likesOptions = @Html.Raw(ViewBag.Likes);
  var expOptions = @Html.Raw(ViewBag.Exponents);

  var wholeData = [];

  for (var k = 0; k < numOfSheets; k++) {
    var first = true;
    var tableProto = "<table class='table'>"
    for (var i = 0; i < likesOptions.length; i++) {
      tableProto += "<tr>";
      for (var j = 0; j < expOptions.length; j++) {
        tableProto += "<td id='rf_" + k + "_" + i + "_" + j + "_FOtd'></td>";
      }
      tableProto += "</tr>";
    }
    tableProto += "</table>";
    document.getElementById("rf_" + k + "FOp").innerHTML += tableProto;
  }

  var datasReady = 0;
  async function loadAllData() {
    for (var k = 0; k < numOfSheets; k++) {
      await loadSingleSheet(k)
    }
  }

  async function loadSingleSheet(sheet_k) {
    await d3.text("http://localhost:8888/EvaluationAnalytics/@Uri.EscapeUriString(ViewBag.Process.Value.Name)/" + sheet_k, function (text) {
      var data = d3.csvParse(text)
      wholeData[sheet_k] = data;
      datasReady++;
      if (datasReady == numOfSheets)
        parseAllData();
    });
  }

  function parseAllData() {
    for (var k = 0; k < numOfSheets; k++) {
      var first = true;
      for (var i = 0; i < likesOptions.length; i++) {
        for (var j = 0; j < expOptions.length; j++) {
          loadSvgData(i, j, k, first);
          first = false;
        }
      }
    }
  }

  function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
  }

  function loadSvgData(i, j, k, first) {
    // append the svg object to the body of the page
    var svg = d3.select("#rf_" + k + "_" + i + "_" + j + "_FOtd")
      .append("svg")
      .attr("width", width + margin.left + margin.right)
      .attr("height", height + margin.top + margin.bottom)
      .append("g")
      .attr("transform",
        "translate(" + margin.left + "," + margin.top + ")");

    //Read the data
    //d3.csv("http://localhost:8888/EvaluationAnalytics/@Uri.EscapeUriString(ViewBag.Process.Value.Name)/" + k + "/" + likesOptions[i] + "/" + expOptions[j],
    //function (data) {
    var data = wholeData[k].filter(e => e.identKey.indexOf(likesOptions[i]) != -1 && e.identKey.indexOf(expOptions[j]) != -1);
    var locSvg = svg;
    if (first) {
      parseData(data, locSvg, "rf_" + k + "FOp", "#rf_" + k + "_" + i + "_" + j + "_FOtd", k);
      first = false;
    } else
      parseData(data, locSvg, null, "#rf_" + k + "_" + i + "_" + j + "_FOtd", k);
    //})

  }

  // Parse the data
  function parseData(data, imageSvg, descriptorId, tooltipDiv, k) {
    console.log(imageSvg);
    console.log(data);
    // group the data: I want to draw one line per group
    var sumstat = d3.nest() // nest function allows to group the calculation per level of a factor
      .key(function (d) { return d.identKey; })
      .entries(data);

    // Add X axis --> it is a date format
    var x = d3.scaleLinear()
      .domain(d3.extent(data, function (d) { return d.screen; }))
      .range([0, width]);
    imageSvg.append("g")
      .attr("transform", "translate(0," + height + ")")
      .call(d3.axisBottom(x).ticks(9));

    var max = maximums[k];
    var y;
    var logS = false;
    if (max == -1) {
      max = Math.max(...data.map(e => Number(e.part)))
      y = d3.scaleLog()
        .domain([1, max])
        .range([height, 0]);
      imageSvg.append("g")
        .call(d3.axisLeft(y));
      logS = true;
    } else {
      y = d3.scaleLinear()
        .domain([0, max])
        .range([height, 0]);
      imageSvg.append("g")
        .call(d3.axisLeft(y));
    }

    // color palette
    var res = sumstat.map(function (d) { return d.key }) // list of group names
    var color = d3.scaleOrdinal()
      .domain(res)
      .range(colorRange)

    addGridLines(imageSvg, x, y);


    console.log(tooltipDiv);
    var tooltip = d3.select(tooltipDiv)
      .append("div")
      .style("opacity", 0)
      .attr("class", "tooltip")
      .style("background-color", "white")
      .style("border", "solid")
      .style("border-width", "2px")
      .style("border-radius", "5px")
      .style("padding", "5px")

    // Draw the line
    drawLines(imageSvg, sumstat, tooltip, color, x, y);

    imageSvg.append("text")
      .attr("y", 0)
      .attr("x", 0)
      .attr('text-anchor', 'start')
      .text(data[0].identKey.split("|")[2]);

    if (descriptorId != null) {
      var descriptor = document.getElementById(descriptorId);
      addLabelToChart(sumstat, descriptor);
    }
  }

  function drawLines(imageSvg, sumstat, tooltip, color, x, y) {

    imageSvg.selectAll(".line")
      .data(sumstat)
      .enter()
      .append("path")
      .attr("fill", "none")
      .attr("stroke", function (d) { return color(d.key) })
      .attr("stroke-width", 3)
      .attr("d", function (d) {
        return d3.line()
          .x(function (d) { return x(d.screen); })
          .y(function (d) { return y(+d.part); })
          (d.values)
      })
      .on("mouseover", function (d) {
        tooltip
          .style("opacity", 1)
      })
      .on("mousemove", function (d) {
        tooltip
          .html("Key: " + d.key)
          .style("left", (d3.mouse(this)[0] + 90) + "px")
          .style("top", (d3.mouse(this)[1] + 50) + "px");
        console.log(d);
      })
      .on("mouseleave", function (d) {
        tooltip
          .style("opacity", 0)
      })

  }

  function addLabelToChart(_sumstat, descriptor) {
    _sumstat.map(function (e, i) {
      var newKey = e.key.split("|");
      descriptor.innerHTML += "<p><span class=\"badge-dot badge-primary\" style=\"background-color: "
        + colorRange[i] + "\"></span>" + newKey[0] + "|" + newKey[1] + "|" + newKey[3] + "</p>";
    });
  }

  function addGridLines(svg, x, y) {

    var xAxis = d3.axisBottom(x)
      .tickSizeInner(-height)
      .tickSizeOuter(0)
      .tickPadding(10);

    var yAxis = d3.axisLeft(y)
      .tickSizeInner(-width)
      .tickSizeOuter(0)
      .tickPadding(10);

    svg.append("g")
      .attr("class", "y axis")
      .call(yAxis);

    svg.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + height + ")")
      .call(xAxis);
  }

  function getRandomColor() {
    var letters = '0123456789abcdef';
    var color = '#';
    for (var i = 0; i < 6; i++) {
      color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
  }


  // Start main load
  loadAllData();
</script>

  @Html.Partial("admin/_footer.cshtml")
