{% extends "base.html" %}
{% block title %}Szczegóły urządzenia - RouterOS Update{% endblock %}
{% block extra_head %}
  <style>
    /* Stylizacja kart w trybie ciemnym */
    body.dark-mode .card {
      background-color: #1e1e1e;
      color: #e0e0e0;
      border-color: #444;
    }
    /* Stylizacja bloku logów – przewijalny, z odpowiednim tłem i kolorem tekstu */
    .log-block {
      background-color: inherit;
      color: inherit;
      padding: 1rem;
      border: 1px solid #ccc;
      border-radius: 0.25rem;
      max-height: 300px;
      overflow-y: auto;
      white-space: pre-wrap;
    }
    /* Stylizacja overlay dla system update */
    #system-update-overlay, #reboot-progress-overlay {
      display: none;
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: rgba(0,0,0,0.7);
      z-index: 1000;
      color: white;
      text-align: center;
      padding-top: 200px;
    }
    #system-update-overlay h3, #reboot-progress-overlay h3 {
      margin-bottom: 20px;
    }
    .progress-container {
      width: 50%;
      margin: 20px auto;
      background: #444;
      border-radius: 5px;
    }
    .progress-bar {
      width: 0%;
      height: 30px;
      background: #4caf50;
      border-radius: 5px;
    }
  </style>
{% endblock %}
{% block content %}
<div class="container">
  <div class="my-4">
    <h2 class="mb-3">Szczegóły urządzenia</h2>
    <nav aria-label="breadcrumb">
      <ol class="breadcrumb">
        <li class="breadcrumb-item"><a href="{{ url_for('devices') }}">Urządzenia</a></li>
        <li class="breadcrumb-item active" aria-current="page">{{ device.ip }}</li>
      </ol>
    </nav>
  </div>

  <!-- Dwukolumnowy układ: dane urządzenia i informacje o systemie -->
  <div class="row">
    <div class="col-md-6">
      <div class="card mb-3">
        <div class="card-header bg-primary text-white">
          Dane urządzenia
        </div>
        <div class="card-body">
          <p><strong>Adres IP:</strong> {{ device.ip }}</p>
          <p><strong>Port:</strong> {{ device.port }}</p>
          <p><strong>Ostatnie sprawdzenie:</strong>
            {% if device.last_check %}{{ device.last_check.strftime('%Y-%m-%d %H:%M:%S') }}{% else %}Brak{% endif %}
          </p>
          <p>
            <strong>System:</strong> {{ device.current_version or 'Brak' }}<br>
            <strong>Firmware:</strong> {{ device.current_firmware or 'N/A' }}<br>
            <strong>Upgrade Firmware:</strong> <b>{{ device.upgrade_firmware or 'N/A' }}</b>
          </p>
          <p>
            <strong>Branch aktualizacji:</strong> {{ device.branch|capitalize }}
          </p>
          <!-- Formularz zmiany branch -->
          <form method="POST" action="{{ url_for('edit_device', device_id=device.id) }}" class="mt-3">
            <div class="input-group">
              <select class="form-select" name="branch">
                <option value="stable" {% if device.branch == 'stable' %}selected{% endif %}>Stable</option>
                <option value="dev" {% if device.branch == 'dev' %}selected{% endif %}>Dev</option>
                <option value="beta" {% if device.branch == 'beta' %}selected{% endif %}>Beta</option>
              </select>
              <button type="submit" class="btn btn-primary ms-2">Zmień branch</button>
            </div>
          </form>
        </div>
      </div>
    </div>
    <div class="col-md-6">
      <div class="card mb-3">
        <div class="card-header bg-primary text-white">
          Informacje o systemie
        </div>
        <div class="card-body">
          {% if resource.error %}
            <div class="alert alert-danger" role="alert">
              Błąd pobierania danych: {{ resource.error }}
            </div>
          {% else %}
            <p><strong>Wersja systemu:</strong> {{ resource.version or 'Brak danych' }}</p>
            <p><strong>Czas pracy:</strong> {{ resource.uptime or 'Brak danych' }}</p>
            <p><strong>Obciążenie CPU:</strong> {{ resource['cpu-load'] or 'Brak' }}%</p>
            <p>
              <strong>Pamięć:</strong>
              {% if resource['free-memory'] and resource['total-memory'] %}
                {{ resource['free-memory'] }} wolnej / {{ resource['total-memory'] }} całkowita
              {% else %}
                Brak danych
              {% endif %}
            </p>
            <p><strong>Wolne miejsce na dysku:</strong> {{ resource['free-hdd-space'] or 'Brak danych' }}</p>
          {% endif %}
        </div>
      </div>
    </div>
  </div>
  
  <!-- Logi urządzenia jako pojedynczy blok tekstu -->
  <div class="card mb-3">
    <div class="card-header bg-secondary text-white">
      Logi urządzenia
    </div>
    <div class="card-body">
      {% if device.last_log %}
        <div class="log-block">
          {{ device.last_log }}
        </div>
      {% else %}
        <p>Brak logów</p>
      {% endif %}
    </div>
  </div>
  
  <!-- Akcje urządzenia -->
  <div class="mb-4">
    <div class="d-flex flex-wrap gap-2">
      <form id="system-update-form" method="POST" action="{{ url_for('update_device', device_id=device.id) }}">
        <button type="submit" class="btn btn-warning">Aktualizuj system</button>
      </form>
      <form id="firmware-update-form" method="POST" action="{{ url_for('update_firmware', device_id=device.id) }}">
        <button type="submit" class="btn btn-danger">Aktualizuj firmware</button>
      </form>
      <a href="{{ url_for('force_check', device_id=device.id) }}" class="btn btn-secondary">Wymuś sprawdzenie</a>
    </div>
    <div class="mt-3">
      <a href="{{ url_for('devices') }}" class="btn btn-outline-secondary">Powrót do listy urządzeń</a>
    </div>
  </div>
  
  <!-- Overlay dla system update (5 minut) -->
  <div id="system-update-overlay">
    <h3>Aktualizacja systemu rozpoczęta...</h3>
    <div class="progress-container">
      <div id="system-update-progress" class="progress-bar"></div>
    </div>
    <p id="system-update-timer">300 sekund</p>
  </div>
  
  <!-- Overlay dla reboot progress (2 minuty) -->
  <div id="reboot-progress-overlay">
    <h3>Restart urządzenia...</h3>
    <div class="progress-container">
      <div id="reboot-progress-bar" class="progress-bar"></div>
    </div>
    <p id="reboot-timer">120 sekund</p>
  </div>
  
  <!-- Div dla firmware restart (komunikat z przyciskiem restartu) -->
  <div id="firmware-restart-div" style="display:none; margin-top:20px;">
    <div class="alert alert-warning">
      Router wymaga ręcznego wykonania polecenia reboot.
    </div>
    <button id="restart-device-btn" class="btn btn-danger">Restart urządzenia</button>
  </div>
  
</div>

<script>
  // System update: Po kliknięciu w formularz system update
  document.getElementById('system-update-form').addEventListener('submit', function(e) {
    e.preventDefault();  // Zatrzymaj standardowe wysłanie formularza
    var overlay = document.getElementById('system-update-overlay');
    overlay.style.display = 'block';
    var timeLeft = 240;
    var progressBar = document.getElementById('system-update-progress');
    var timerDisplay = document.getElementById('system-update-timer');
    var interval = setInterval(function(){
      timeLeft--;
      var percent = ((240 - timeLeft) / 240) * 100;
      progressBar.style.width = percent + '%';
      timerDisplay.textContent = timeLeft + ' sekund';
      if(timeLeft <= 0){
        clearInterval(interval);
        // Po zakończeniu 5 minut wykonaj polecenie "Wymuś sprawdzenie"
        fetch('{{ url_for("force_check", device_id=device.id) }}', { method: 'GET' })
          .then(function(response){
            location.reload();
          })
          .catch(function(error){ console.error('Błąd force check:', error); });
      }
    }, 1000);
    // Opcjonalnie wysyłamy formularz AJAX, aby rozpocząć aktualizację systemu
    fetch(this.action, { method: 'POST' })
      .then(function(response){ /* opcjonalna obsługa odpowiedzi */ })
      .catch(function(error){ console.error('Błąd aktualizacji systemu:', error); });
  });

  // Firmware update: Po kliknięciu w formularz firmware update
  document.getElementById('firmware-update-form').addEventListener('submit', function(e) {
    e.preventDefault();  // Zatrzymaj standardowe wysłanie formularza
    fetch(this.action, { method: 'POST' })
      .then(function(response){ /* opcjonalna obsługa odpowiedzi */ })
      .catch(function(error){ console.error('Błąd aktualizacji firmware:', error); });
    // Pokaż div z komunikatem o reboot i przyciskiem restartu
    document.getElementById('firmware-restart-div').style.display = 'block';
  });

  // Restart urządzenia: Po kliknięciu przycisku restart wysyłamy komendę reboot,
  // a następnie pokazujemy overlay z 2-minutowym paskiem postępu
  document.getElementById('restart-device-btn').addEventListener('click', function() {
    fetch('{{ url_for("restart_device", device_id=device.id) }}', {
      method: 'POST'
    }).then(function(response){
      if(response.ok){
        alert('Komenda reboot wysłana.');
        // Pokaż overlay dla reboot progress
        var rebootOverlay = document.getElementById('reboot-progress-overlay');
        rebootOverlay.style.display = 'block';
        var timeLeft = 90; 
        var progressBar = document.getElementById('reboot-progress-bar');
        var timerDisplay = document.getElementById('reboot-timer');
        var interval = setInterval(function(){
          timeLeft--;
          var percent = ((90 - timeLeft) / 90) * 100;
          progressBar.style.width = percent + '%';
          timerDisplay.textContent = timeLeft + ' sekund';
          if(timeLeft <= 0){
            clearInterval(interval);
            // Po 2 minutach wykonaj polecenie "Wymuś sprawdzenie"
            fetch('{{ url_for("force_check", device_id=device.id) }}', { method: 'GET' })
              .then(function(response){
                location.reload();
              })
              .catch(function(error){ console.error('Błąd force check:', error); });
          }
        }, 1000);
      } else {
        alert('Błąd podczas wysyłania komendy reboot.');
      }
    }).catch(function(error){
      alert('Błąd: ' + error);
    });
  });
</script>
{% endblock %}