{% extends "pages/base.html" %}
{% load i18n %}

{% block title %}{% trans "Charge Points" %}{% endblock %}

{% block content %}
<h1>{% trans "Charge Points" %}</h1>
{% if show_demo_notice %}
<div id="demo-notice" class="alert alert-info position-relative" role="alert" data-session-key="ocppDemoNoticeDismissed">
  <button
    type="button"
    class="btn-close btn-close-white position-absolute top-0 end-0 mt-2 me-2"
    data-demo-notice-dismiss
    aria-label="{% trans "Dismiss demo notice" %}"
  ></button>
  <h2 class="h5 mb-2">{% trans "Demo OCPP 1.6 CPMS (Charge Point Management System)" %}</h2>
  <p class="mb-1">{% trans "Everyone is welcome to use this demo to test their charge points." %}</p>
  <p class="mb-1">{% blocktrans with limit=ws_rate_limit %}Rate limiting applies (maximum {{ limit }} simultaneous connections per IP).{% endblocktrans %}</p>
  <p class="mb-0">{% blocktrans %}Use the following WebSocket URL format, replacing &lt;CHARGE_POINT_ID&gt; with your charge point identifier:{% endblocktrans %}</p>
  <pre class="mb-0"><code>{{ demo_ws_url }}</code></pre>
  <p class="mb-0 mt-2">
    {% blocktrans trimmed %}You may also provide the identifier as a query parameter using any of the following names: <code>cid</code>, <code>chargePointId</code>, <code>charge_point_id</code>, <code>chargeBoxId</code>, <code>charge_box_id</code>, or <code>chargerId</code>.{% endblocktrans %}
  </p>
</div>
<script>
  (function () {
    if (typeof window === 'undefined' || typeof document === 'undefined') {
      return;
    }

    const notice = document.getElementById('demo-notice');
    if (!notice) {
      return;
    }

    const dismissButton = notice.querySelector('[data-demo-notice-dismiss]');
    if (!dismissButton) {
      return;
    }

    const storage = (() => {
      try {
        if (!('sessionStorage' in window)) {
          return null;
        }
        const testKey = '__ocppDemoNoticeTest__';
        window.sessionStorage.setItem(testKey, '1');
        window.sessionStorage.removeItem(testKey);
        return window.sessionStorage;
      } catch (error) {
        return null;
      }
    })();

    const storageKey = notice.dataset.sessionKey || 'ocppDemoNoticeDismissed';
    const dismissed = storage ? storage.getItem(storageKey) === '1' : false;
    if (dismissed) {
      notice.classList.add('d-none');
      return;
    }

    dismissButton.addEventListener('click', () => {
      notice.classList.add('d-none');
      if (!storage) {
        return;
      }
      try {
        storage.setItem(storageKey, '1');
      } catch (error) {
        // Ignore storage errors (e.g., disabled cookies)
      }
    });
  })();
</script>
{% endif %}
<table class="table">
  <thead>
    <tr>
      <th>{% trans "Name" %}</th>
      <th>{% trans "Serial Number" %}</th>
      <th class="text-end">{% trans "Total kW" %}</th>
      <th class="text-end">{% trans "Today's kW" %}</th>
      <th>{% trans "Status" %}</th>
    </tr>
  </thead>
  <tbody data-dashboard-table-body>
    {% include "ocpp/includes/dashboard_table_rows.html" %}
  </tbody>
</table>
{% if request.user.is_staff %}
<p class="text-center mt-3">
  <a href="{% url 'admin:ocpp_charger_changelist' %}">{% trans "Configure" %}</a>
</p>
{% endif %}
{% endblock %}

{% block live_update_script %}
      (function () {
        const intervalSeconds = Number({{ request.live_update_interval|default_if_none:5 }});
        if (!intervalSeconds || intervalSeconds < 0) {
          return;
        }
        const tableBody = document.querySelector('[data-dashboard-table-body]');
        if (!tableBody) {
          setInterval(() => location.reload(), intervalSeconds * 1000);
          return;
        }
        const requestUrl = new URL(window.location.href, window.location.origin);
        requestUrl.searchParams.set('partial', 'table');
        const fetchUrl = requestUrl.toString();

        async function refreshTable() {
          try {
            const response = await fetch(fetchUrl, {
              headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'Accept': 'application/json',
              },
              credentials: 'same-origin',
            });
            if (!response.ok) {
              return;
            }
            const data = await response.json();
            if (!data || typeof data.html !== 'string') {
              return;
            }
            tableBody.innerHTML = data.html;
          } catch (error) {
            console.error('Failed to refresh dashboard table', error);
          }
        }

        refreshTable();

        setInterval(() => {
          if (document.visibilityState === 'hidden') {
            return;
          }
          refreshTable();
        }, intervalSeconds * 1000);

        document.addEventListener('visibilitychange', () => {
          if (document.visibilityState === 'visible') {
            refreshTable();
          }
        });
      })();
{% endblock %}
