$(document).ready(() => {
  let currentSensor = "s1";

  function drawPlot(d) {
    Plotly.newPlot("signal", [
      {
        x: d.x,
        y: d.y,
        type: "scatter",
        mode: "lines",
        line: { color: "red", width: 2 },
        marker: {
          color: "cyan",
          size: 0,
          line: { color: "white", width: 1 }
        }
      }
    ], {
      paper_bgcolor: "#111",
      plot_bgcolor: "#111",
      font: { color: "#eee" },
      title: { text: d.name },
      xaxis: {
        title: { text: "Czas" },
        type: "date",
        tickformat: "%H:%M:%S",
        tickmode: "auto",
        nticks: 10,
        gridcolor: "#333",
        linecolor: "#aaa",
        tickcolor: "#aaa"
      },
      yaxis: {
        title: { text: "Wartość" },
        range: [-1.1, 1.1],
        gridcolor: "#333",
        linecolor: "#aaa",
        tickcolor: "#aaa"
      }
    });

    $("span.signal-name").html(d.name);
  }

  function loadSignal() {
    $.get(`/api/signal/${currentSensor}`, (d, status) => {
      drawPlot(d);
    });
  }

  $(".sensor-btn").on("click", function() {
    currentSensor = $(this).data("sensor");
    loadSignal();
  });

  loadSignal();

  setInterval(() => {
    loadSignal();
  }, 1000);
});