@model Watcher.ViewModels.ServerDetailsViewModel
@{
    ViewData["Title"] = "Serverübersicht";
}

<head>
    <link rel="stylesheet" href="~/css/main.css" />
    <link rel="stylesheet" href="~/css/server-detail.css" />
</head>

<div id="server-cards-container">

    <div class="container mt-4">
        <div class="card shadow-sm">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0">
                    <i class="bi bi-hdd-network me-2 text-primary"></i>@Model.Name
                </h5>
                <span class="badge @(Model.IsOnline ? "bg-success" : "bg-danger")">
                    <i class="bi @(Model.IsOnline ? "bi-check-circle" : "bi-x-circle") me-1"></i>
                    @(Model.IsOnline ? "Online" : "Offline")
                </span>
            </div>

            <div class="infocard row g-4 mb-4">
                <div class="info col-6 text-text col-lg-3">
                    <div><i class="bi bi-globe me-1"></i><strong>IP:</strong> @Model.IPAddress</div>
                    <div><i class="bi bi-pc-display me-1"></i><strong>Typ:</strong> @Model.Type</div>
                    <div><i class="bi bi-calendar-check me-1"></i><strong>Erstellt:</strong>
                        @Model.CreatedAt.ToLocalTime().ToString("dd.MM.yyyy HH:mm")</div>
                    <div><i class="bi bi-clock me-1"></i><strong>Last-Seen:</strong>
                        @Model.LastSeen.ToLocalTime().ToString("dd.MM.yyyy HH:mm")</div>
                </div>
                <div class="hardware col-6 text-text col-lg-3">
                    <div><i class="bi bi-cpu me-1"></i><strong>CPU:</strong> @(Model.CpuType ?? "not found") </div>
                    <div><i class="bi bi-cpu me-1"></i><strong>CPU-Kerne: </strong> @Model.CpuCores </div>
                    <div><i class="bi bi-gpu-card me-1"></i><strong>GPU:</strong> @(Model.GpuType ?? "not found")
                    </div>
                    <div><i class="bi bi-memory me-1"></i><strong>RAM:</strong> @(Model.RamSize) </div>
                    <div><i class="bi bi-hdd me-1"></i><strong>Disk Space:</strong> ... </div>
                </div>
                <div class="hardware col-6 text-text col-lg-3">
                    <div class="card-footer text-end">
                        <a asp-action="EditServer" asp-route-id="@Model.Id" class="btn btn-outline-primary me-2">
                            <i class="bi bi-pencil"></i> Bearbeiten
                        </a>
                        <form asp-action="Delete" asp-route-id="@Model.Id" method="post" class="d-inline"
                            onsubmit="return confirm('Diesen Server wirklich löschen?');">
                            <button type="submit" class="btn btn-outline-danger">
                                <i class="bi bi-trash"></i> Löschen
                            </button>
                        </form>
                    </div>
                </div>

            </div>

        </div>
    </div>

    <div class="mt-4">
        <h6><i class="bi bi-graph-up me-1"></i>CPU Last</h6>
        <div class="graphcontainer p-4 text-center text-muted">
            <canvas class="graph" id="cpuUsageChart"></canvas>
        </div>
    </div>
    <div class="mt-4">
        <h6><i class="bi bi-graph-up me-1"></i>RAM Last</h6>
        <div class="graphcontainer p-4 text-center text-muted">
            <canvas class="graph" id="ramUsageChart"></canvas>
        </div>
    </div>
    <div class="mt-4">
        <h6><i class="bi bi-graph-up me-1"></i>GPU Last</h6>
        <div class="graphcontainer p-4 text-center text-text">
            <canvas class="graph" id="gpuUsageChart"></canvas>
        </div>
    </div>

</div>

@section Scripts {
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script>
        document.addEventListener("DOMContentLoaded", function () {
            const ctx_cpu = document.getElementById('cpuUsageChart').getContext('2d');
            const ctx_ram = document.getElementById('ramUsageChart').getContext('2d');
            const ctx_gpu = document.getElementById('gpuUsageChart').getContext('2d');

            const cpuChart = new Chart(ctx_cpu, {
                type: 'line',
                data: {
                    labels: [],
                    datasets: [{
                        label: 'CPU Last (%)',
                        data: [],
                        backgroundColor: 'rgba(255, 99, 132, 0.2)',
                        fill: true,
                        tension: 0.3,
                        pointRadius: 3
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        y: {
                            beginAtZero: true,
                            max: 100,
                            title: {
                                display: true,
                                text: 'Auslastung in %'
                            }
                        },
                        x: {
                            title: {
                                display: false,
                                text: 'Zeit'
                            }
                        }
                    }
                }
            });

            const ramChart = new Chart(ctx_ram, {
                type: 'line',
                data: {
                    labels: [],
                    datasets: [{
                        label: 'RAM Last (%)',
                        data: [],
                        backgroundColor: 'rgba(255, 99, 132, 0.2)',
                        fill: true,
                        tension: 0.3,
                        pointRadius: 3
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        y: {
                            beginAtZero: true,
                            max: 100,
                            title: {
                                display: true,
                                text: 'Auslastung in %'
                            }
                        },
                        x: {
                            title: {
                                display: false,
                                text: 'Zeit'
                            }
                        }
                    }
                }
            });

            const gpuChart = new Chart(ctx_gpu, {
                type: 'line',
                data: {
                    labels: [],
                    datasets: [{
                        label: 'GPU Last (%)',
                        data: [],
                        backgroundColor: 'rgba(255, 99, 132, 0.2)',
                        fill: true,
                        tension: 0.3,
                        pointRadius: 3
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        y: {
                            beginAtZero: true,
                            max: 100,
                            title: {
                                display: true,
                                text: 'Auslastung in %'
                            }
                        },
                        x: {
                            title: {
                                display: false,
                                text: 'Zeit'
                            }
                        }
                    }
                }
            });

            async function loadCpuData() {
                try {
                    const response = await fetch('/monitoring/cpu-usage?serverId=@Model.Id');
                    if (!response.ok) {
                        throw new Error(`HTTP-Fehler: ${response.status}`);
                    }

                    const data = await response.json();

                    if (!Array.isArray(data) || data.length === 0) {
                        console.warn('Keine CPU-Daten empfangen.');
                        return;
                    }

                    cpuChart.data.labels = data.map(d => d.label ?? '');
                    cpuChart.data.datasets[0].data = data.map(d => Number(d.data));

                    cpuChart.update();
                } catch (err) {
                    console.error('Fehler beim Laden der CPU-Daten:', err);
                }
            }

            async function loadRamData() {
                try {
                    const response = await fetch('/monitoring/ram-usage?serverId=@Model.Id');
                    if (!response.ok) {
                        throw new Error(`HTTP-Fehler: ${response.status}`);
                    }

                    const data = await response.json();

                    if (!Array.isArray(data) || data.length === 0) {
                        console.warn('Keine RAM-Daten empfangen.');
                        return;
                    }

                    ramChart.data.labels = data.map(d => d.label ?? '');
                    ramChart.data.datasets[0].data = data.map(d => Number(d.data));

                    ramChart.update();
                } catch (err) {
                    console.error('Fehler beim Laden der RAM-Daten:', err);
                }
            }

            async function loadGpuData() {
                try {
                    const response = await fetch('/monitoring/gpu-usage?serverId=@Model.Id');
                    if (!response.ok) {
                        throw new Error(`HTTP-Fehler: ${response.status}`);
                    }

                    const data = await response.json();

                    if (!Array.isArray(data) || data.length === 0) {
                        console.warn('Keine GPU-Daten empfangen.');
                        return;
                    }

                    gpuChart.data.labels = data.map(d => d.label ?? '');
                    gpuChart.data.datasets[0].data = data.map(d => Number(d.data));

                    gpuChart.update();
                } catch (err) {
                    console.error('Fehler beim Laden der GPU-Daten:', err);
                }
            }

            // Initiales Laden
            loadCpuData();
            loadRamData();
            loadGpuData();

            // Alle 30 Sekunden aktualisieren
            setInterval(loadCpuData, 30000);
            setInterval(loadRamData, 30000);
            setInterval(loadGpuData, 30000);
        });
    </script>
}