{% extends "base.html" %}
{% block title %}Lista serwerów - /etc/hosts Manager{% endblock %}

{% block extra_css %}
{{ super() }}
<style>
  .tooltip-inner {
    max-width: 300px;
    text-align: left;
  }
</style>
{% endblock %}

{% block content %}
<div class="card">
  <div class="card-header">
    <h2>Lista serwerów</h2>
  </div>
  <div class="card-body table-responsive">
    <table class="table table-striped align-middle">
      <thead>
        <tr>
          <th>ID</th>
          <th>Nazwa serwera</th>
          <th>Użytkownik</th>
          <th>Port</th>
          <th>Typ</th>
          <th>Uwierzytelnianie</th>
          <th>Wybrany plik /etc/hosts</th>
          <th>Auto Deploy</th>
          <th>Auto Backup</th>
          <th>Wyłącz CIDR/regex deploy</th>
          <th>Akcje</th>
        </tr>
      </thead>
      <tbody>
        {% for h in hosts %}
        <tr>
          <td>{{ h.id }}</td>
          <td data-bs-toggle="tooltip" data-bs-placement="top" title="{{ h.raw_ip }}">
            {% if h.use_daemon and h.type == 'linux' and h.daemon_url %}
              {{ h.resolved_daemon }}
            {% else %}
              {{ h.resolved_hostname }}
            {% endif %}
          </td>
          
           
          <td>
            {% if h.use_daemon and h.type == 'linux' %}
              <em>—</em>
            {% else %}
              {{ h.username }}
            {% endif %}
          </td>
          <td>
            {% if h.use_daemon and h.type == 'linux' %}
              <em>—</em>
            {% else %}
              {{ h.port }}
            {% endif %}
          </td>
          <td>
            {% if h.type == 'linux' %}
              Linux{% if h.use_daemon %} (Demon){% endif %}
            {% else %}
              Mikrotik
            {% endif %}
          </td>
          <td>
            {% if h.use_daemon and h.type == 'linux' %}
              <em>- używa Demona -</em>
            {% else %}
              {% if h.auth_method == 'password' %}
                Hasło
              {% elif h.auth_method == 'ssh_key' %}
                Klucz SSH
              {% elif h.auth_method == 'global_key' %}
                Globalny klucz
              {% else %}
                {{ h.auth_method }}
              {% endif %}
            {% endif %}
          </td>
          <td>
            {% if h.preferred_hostfile %}
              {{ h.preferred_hostfile.title }}
            {% else %}
              (Default)
            {% endif %}
          </td>
          <td>
            <form method="POST" action="{{ url_for('update_host_automation', id=h.id) }}" style="display:inline;">
              <input type="hidden" name="setting" value="auto_deploy">
              <input type="checkbox" name="enabled" value="1"
                     onchange="this.form.submit()" {% if h.auto_deploy_enabled %}checked{% endif %}>
            </form>
          </td>
          <td>
            <form method="POST" action="{{ url_for('update_host_automation', id=h.id) }}" style="display:inline;">
              <input type="hidden" name="setting" value="auto_backup">
              <input type="checkbox" name="enabled" value="1"
                     onchange="this.form.submit()" {% if h.auto_backup_enabled %}checked{% endif %}>
            </form>
          </td>
          <td>
            <form method="POST" action="{{ url_for('update_host_automation', id=h.id) }}" style="display:inline;">
              <input type="hidden" name="setting" value="disable_regex">
              <input type="checkbox" name="enabled" value="1"
                     onchange="this.form.submit()" {% if h.disable_regex_deploy %}checked{% endif %}>
            </form>
            <td>
              <div class="d-flex flex-wrap gap-1">
                <a href="{{ url_for('edit_server', id=h.id) }}" class="btn btn-primary btn-sm">Edytuj</a>
                
                {% if h.use_daemon and h.type == 'linux' %}
                <!-- Serwery z demonem – nowy sposób -->
                <button class="btn btn-info btn-sm test-daemon-btn" data-host-id="{{ h.id }}">
                  Testuj
                </button>
                {% else %}
                <!-- Dotychczasowy sposób dla SSH/Mikrotik -->
                <a href="{{ url_for('test_server_connection', id=h.id) }}" class="btn btn-info btn-sm">Testuj</a>
                {% endif %}
            
                <a href="{{ url_for('server_backup', host_id=h.id) }}" class="btn btn-success btn-sm">Backup</a>
                <form method="GET" action="{{ url_for('delete_server', id=h.id) }}" style="display:inline;">
                  <button type="submit" class="btn btn-danger btn-sm">Usuń</button>
                </form>
              </div>
            </td>
        </tr>
        {% endfor %}
      </tbody>
      
    </table>
  </div>
</div>




<div class="mt-3 text-center">
  <a href="{{ url_for('add_server') }}" class="btn btn-secondary">Dodaj nowy serwer</a>
  <a href="{{ url_for('import_servers') }}" class="btn btn-secondary">Importuj z CSV</a>
  <a href="{{ url_for('export_servers_to_csv') }}" class="btn btn-secondary">Eksportuj do CSV</a>
</div>

<!-- Modal z informacjami -->
<div class="modal fade" id="serverInfoModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Informacje o serwerze</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <p><strong>Host:</strong> <span id="modal-hostname"></span></p>
        
        <label><strong>CPU:</strong></label>
        <div class="progress mb-3">
          <div id="modal-cpu" class="progress-bar" role="progressbar"></div>
        </div>

        <label><strong>Pamięć:</strong></label>
        <div class="progress mb-3">
          <div id="modal-mem" class="progress-bar bg-warning" role="progressbar"></div>
        </div>

        <label><strong>Dysk:</strong></label>
        <div class="progress mb-3">
          <div id="modal-disk" class="progress-bar bg-success" role="progressbar"></div>
        </div>

        <p><strong>Czas działania:</strong> <span id="modal-uptime"></span></p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Zamknij</button>
      </div>
    </div>
  </div>
</div>

{% endblock %}

{% block extra_js %}
<script>
function secondsToDhms(seconds) {
  seconds = Math.floor(seconds);
  const d = Math.floor(seconds / (3600*24));
  const h = Math.floor(seconds % (3600*24) / 3600);
  const m = Math.floor(seconds % 3600 / 60);
  const s = Math.floor(seconds % 60);
  return `${d} dni, ${h} godz, ${m} min, ${s} sek`;
}

document.querySelectorAll('.test-daemon-btn').forEach(btn => {
  btn.addEventListener('click', function() {
    fetch(`/server-info/${this.dataset.hostId}`)
      .then(res => res.json())
      .then(data => {
        if (data.error) return alert(`Błąd: ${data.error}`);
        document.getElementById('modal-hostname').textContent = data.hostname;
        document.getElementById('modal-ip').textContent = data.ip;
        document.getElementById('modal-cpu').textContent = data.cpu;
        document.getElementById('modal-mem').textContent = data.mem;
        document.getElementById('modal-disk').textContent = data.disk;
        document.getElementById('modal-uptime').textContent = secondsToDhms(data.uptime_seconds);
        new bootstrap.Modal(document.getElementById('serverInfoModal')).show();
      })
      .catch(() => alert('Błąd podczas pobierania danych.'));
  });
});
</script>
{% endblock %}