{% extends 'base.html' %}
{% block content %}
<div class="container-fluid">
  <h1 class="mt-4">센서</h1>
  <p></p>
  <hr>

  <div class="row">
    <!-- 왼쪽: 세로 스크롤 가능한 테이블 -->
    <div class="col-md-6">
      <h5>센서데이터출력</h5>
      <div style="max-height: 600px; overflow-y: auto; border: 1px solid #ddd; border-radius: 5px;">
        <table class="table table-hover mb-0">
          <thead class="table-light">
            <tr>
              <th>번호</th>
              <th>구분</th>
              <th>데이터</th>
              <th>날짜</th>        
            </tr>
          </thead>
          <tbody>
            {% for row in rows %}
            <tr {% if row[2] >= 100 %} style="background-color: rgba(255, 0, 0, 0.2);" {% endif %}>
              <td>{{ row[0] }}</td>
              <td>{{ row[1] }}</td>
              <td>{{ row[2] }}</td>
              <td>{{ row[3] }}</td>        
            </tr>
            {% endfor %}
          </tbody>
        </table>
      </div>
    </div>

    <!-- 오른쪽: 고정 크기 차트 -->
    <div class="col-md-6 d-flex flex-column">
      <h5>센서데이터 그래프 출력</h5>
      <div style="flex: 1; display: flex; align-items: center; justify-content: center;">
        <canvas id="sensorChart" style="width: 100%; height: 400px;"></canvas>
      </div>
    </div>
  </div>
</div>

<!-- Chart.js 불러오기 -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
  const labels = {{ labels | tojson }};
  const data = {{ data | tojson }};

  // 조건부 색상: 값이 100 이상이면 빨간색, 아니면 파란색
  const pointColors = data.map(v => v >= 100 ? 'rgba(255,0,0,1)' : 'rgba(54,162,235,1)');
  const bgColors = data.map(v => v >= 100 ? 'rgba(255,0,0,0.3)' : 'rgba(54,162,235,0.2)');

  const ctx = document.getElementById('sensorChart').getContext('2d');
  const sensorChart = new Chart(ctx, {
    type: 'line',
    data: {
      labels: labels,
      datasets: [{
        label: '센서 데이터',
        data: data,
        borderColor: 'rgba(54, 162, 235, 1)',
        backgroundColor: 'rgba(54, 162, 235, 0.1)',
        fill: true,
        tension: 0.3,
        pointRadius: 5,
        pointBackgroundColor: pointColors, // 조건부 색상 적용
        pointBorderColor: pointColors,
      }]
    },
    options: {
      maintainAspectRatio: false,
      responsive: true,
      plugins: {
        legend: { display: true }
      },
      scales: {
        y: { beginAtZero: true }
      }
    }
  });
</script>
{% endblock %}
