@section('title', 'Hasil Tes')
@extends('user.layouts.index')
@section('content')
  <!-- Page Title -->
  <div class="page-title">
    <div class="heading">
      <div class="container">
        <div class="row d-flex justify-content-center text-center">
          <div class="col-lg-8">
            <h1 class="heading-title">Hasil Tes Anda</h1>
            <p class="mb-0">
              Cek hasil tes kamu dari sini ya, jika kamu sudah mendapatkan kode dari email setelah melakukan booking, kamu bisa melihat hasil tes disini dengan kode tadi.
            </p>
          </div>
        </div>
      </div>
    </div>
    <nav class="breadcrumbs">
      <div class="container">
        <ol>
          <li><a href="index.html">Home</a></li>
          <li class="current">Hasil Tes</li>
        </ol>
      </div>
    </nav>
  </div><!-- End Page Title -->

  <!-- About Section -->
  <section id="about" class="about section">
    <div class="container" data-aos="fade-up" data-aos-delay="100">
      <table class="table" id="table-data-hasil-ujian">
        <thead>
          <tr>
            <th>No</th>
            <th>Pertanyaan</th>
            <th>Jawaban</th>
          </tr>
        </thead>
        <tbody></tbody>
      </table>
    </div>

    <div class="container">
      <div class="row">
        <div class="col-lg-12">
          <h2 class="title">Grafik Kecepatan Mata</h2>
          <canvas id="velocityChart"></canvas>
        </div>
        <div class="col-lg-12 mt-5">
          <h2 class="title">Heatmap Pergerakan Mata</h2>
          <div style="position: relative; aspect-ratio: 16/9;">
            <img src="{{ asset('assets/users/assets/img/overlay/overlay.png') }}" style="width:100%; height:100%; object-fit: cover;">
            <div id="heatmapChart" style="aspect-ratio: 16/9;"></div>
          </div>
        </div>
      </div>
    </div>
  </section><!-- /About Section -->

  <div class="toast-container position-fixed bottom-0 end-0 p-3">
    <div id="liveToast" class="toast" role="alert" aria-live="assertive" aria-atomic="true">
      <div class="toast-header">
        <strong class="me-auto"><i class="bi bi-exclamation-triangle"></i> Kesalahan</strong>
        <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
      </div>
      <div class="toast-body">
        {{ session('error') }}
      </div>
    </div>
  </div>

@endsection

@section('script')
  <script>
    const ws = new WebSocket('{{ env("WEBSOCKET_URL") }}');
    let table = null;
    let data_tobii = null;
    let heatmapContainer = null;
    let clientWidth = null;
    let clientHeight = null;
    let mappedHeatmapData = null;
    let scaleX = null;
    let scaleY = null;
    let heatmapInstance = null;

    function renderVelocityChart(timeseries) {
      const base = timeseries.timestamp[0];
      const labels = timeseries.timestamp.map(t => (t - base) / 1000);
      const ctx = document.getElementById('velocityChart').getContext('2d');

      new Chart(ctx, {
        type: 'line',
        data: {
          labels: labels,
          datasets: [{
            label: 'Velocity',
            data: timeseries.velocity,
            borderWidth: 2,
            tension: 0.3
          }]
        },
        options: {
          responsive: true,
          plugins: {
            tooltip: {
              callbacks: {
                label: function(context) {
                  return "Velocity: " + context.raw.toFixed(4);
                }
              }
            }
          },
          scales: {
            x: {
              display: false
            }
          }
        }
      });
    }

    async function loadData(data) {
      const res = await fetch("{{ env('PYTHON_API_URL') }}/extract", {
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify(data)
      });

      const result = await res.json();
      if(result != null) {
        renderVelocityChart(result.timeseries);
        mappedHeatmapData = result.heatmap.map(point => ({
          x: point.x * scaleX,
          y: point.y * scaleY,
          value: point.value
        }));
        heatmapInstance.setData({
          max: 10,
          data: mappedHeatmapData
        });
        heatmapContainer.style.removeProperty('position');
      }
    }

    $(document).ready(function() {
      table = new DataTable("#table-data-hasil-ujian", {
        searching: false,
        paging: false,
        ajax: {
          url: '{{ route('hasil-tes.getAllAnswer', ['id_test_sessions' => $id_session]) }}',
          dataSrc: 'data' // Specify the key containing the data array
        },
        columns: [
          {
            data: null,
            render: function(data, type, row, meta) {
              return meta.row + 1;
            }
          },
          {
            data: 'soal'
          },
          {
            data: null,
            render: function(data, type, row) {
              let renderedJawaban = null;
              if(row.jawaban_key == 'a') {
                renderedJawaban = `<span class="badge text-bg-primary">${row.jawaban}</span>`;
              } else if(row.jawaban_key == 'b') {
                renderedJawaban = `<span class="badge" style="background-color: #fc7938; color: white;">${row.jawaban}</span>`;
              } else if(row.jawaban_key == 'c') {
                renderedJawaban = `<span class="badge text-bg-danger">${row.jawaban}</span>`;
              } else if(row.jawaban_key == 'd') {
                renderedJawaban = `<span class="badge text-bg-warning">${row.jawaban}</span>`;
              } else if(row.jawaban_key == 'e') {
                renderedJawaban = `<span class="badge text-bg-success">${row.jawaban}</span>`;
              } else {
                renderedJawaban = `<span class="badge text-bg-secondary">${row.jawaban}</span>`;
              }
              return renderedJawaban;
            }
          }
        ]
      });

      ws.onopen = () => {
        console.log("Connected to WebSocket");

        ws.send(JSON.stringify({
          type: 'get_json_file',
          session_id: '{{ $id_session }}'
        }));

        ws.onmessage = (event) => {
          const data = JSON.parse(event.data);
          if(data.type === 'json_file_data') {
            if(data.data != null) {
              data_tobii = data.data;

              heatmapContainer = document.getElementById('heatmapChart');
              clientWidth = heatmapContainer.clientWidth;
              clientHeight = heatmapContainer.clientHeight;
              scaleX = clientWidth / 1366;
              scaleY = clientHeight / 768;
              
              heatmapInstance = h337.create({
                container: heatmapContainer,
                radius: 40,
                maxOpacity: 0.6,
                blur: 0.85
              });
              loadData(data_tobii);
            }
          }
        };
      };
    });
  </script>

  @if (session('error'))
    <script>
      $(document).ready(function() {
        var toast = new bootstrap.Toast(document.getElementById('liveToast'));
        toast.show();
      });
    </script>
  @endif
@endsection