<div class="chart-container">
  <canvas id="networkChart" height="320"></canvas>
</div>
<script>
  const netCtx = document.getElementById("networkChart");
  const initialHistory = {{ network_history | tojson }};
  const netcss = getComputedStyle(document.documentElement);
  const netRxColor = netcss.getPropertyValue("--metric-net-rx").trim();
  const netTxColor = netcss.getPropertyValue("--metric-net-tx").trim();

  const netChart = new Chart(
    document.getElementById("networkChart"),
    {
      type: "line",
      data: {
        datasets: []
      },
      options: {
        responsive: true,
        animation: false,
        maintainAspectRatio: false,
        parsing: false,
        scales: {
          x: {
            type: "timeseries",
            display: true,
            title: {
              display: true,
              text: "Time"
            }
          },
          y: {
            beginAtZero: true,
            ticks: { callback: v => v + ' KB/s' },
            title: {
              display: true,
              text: "Transfer Rate"
            }
          },
        },
        interaction: {
          mode: 'nearest',
          axis: 'x',
          intersect: false
        },
        plugins: {
          legend: {
            display: true
          },
          tooltip: {
            mode: 'index',
          }
        }
      }
    }
  );

  for (const [iface, samples] of Object.entries(initialHistory)) {
    netChart.data.datasets.push({
      label: iface + " ↓",
      pointRadius: 0,
      borderColor: netRxColor,
      backgroundColor: netRxColor,
      data: samples.map(s => ({
        x: s.t * 1000,
        y: s.rx_bps / 1024
      }))
    });

    netChart.data.datasets.push({
      label: iface + " ↑",
      pointRadius: 0,
      borderColor: netTxColor,
      backgroundColor: netTxColor,
      data: samples.map(s => ({
        x: s.t * 1000,
        y: s.tx_bps / 1024
      }))
    });
  }

  netChart.update();

  window.BussDCC.on("ui.system.network.usage.updated", (payload) => {
    let net = payload.data;
    for (const iface of net.interfaces) {
      const rxDataset = netChart.data.datasets.find(d => d.label === iface.interface + " ↓");
      const txDataset = netChart.data.datasets.find(d => d.label === iface.interface + " ↑");

      if (rxDataset) {
        rxDataset.data.push({
          x: payload.timestamp * 1000,
          y: iface.rx_bps / 1024
        });
      }

      if (txDataset) {
        txDataset.data.push({
          x: payload.timestamp * 1000,
          y: iface.tx_bps / 1024
        });
      }
    }

    const cutoff = payload.timestamp - 300;

    for (const dataset of netChart.data.datasets) {
      dataset.data = dataset.data.filter(p => p.x/1000 >= cutoff);
    }

    netChart.update("none");
  });
</script>
