// .NET Packages
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
// Local Namespaces
using Watcher.Data;
using Watcher.ViewModels;

namespace Watcher.Controllers
{
    [Authorize]
    public class HomeController : Controller
    {
        // Datenbankverbindung
        private readonly AppDbContext _context;

        // Logging einbinden
        private readonly ILogger<HomeController> _logger;

        // HomeController Constructor
        public HomeController(AppDbContext context, ILogger<HomeController> logger)
        {
            _context = context;
            _logger = logger;
        }

        // Dashboard unter /home/index
        public async Task<IActionResult> Index()
        {
            var preferredUserName = User.FindFirst("preferred_username")?.Value;


            var user = await _context.Users
                .Where(u => u.Username == preferredUserName)
                .FirstOrDefaultAsync();

            var viewModel = new DashboardViewModel
            {
                ActiveServers = await _context.Servers.CountAsync(s => s.IsOnline),
                OfflineServers = await _context.Servers.CountAsync(s => !s.IsOnline),
                RunningContainers = await _context.Containers.CountAsync(c => c.IsRunning),
                FailedContainers = await _context.Containers.CountAsync(c => !c.IsRunning),
                LastLogin = user?.LastLogin ?? DateTime.MinValue
            };

            return View(viewModel);
        }

        // Funktion für /Views/Home/Index.cshtml um das DashboardStats-Partial neu zu laden.
        // Die Funktion wird nicht direkt aufgerufen, sondern nur der /Home/DashboardStats Endpoint angefragt.
        public IActionResult DashboardStats()
        {
            var servers = _context.Servers.ToList();
            var containers = _context.Containers.ToList();

            var now = DateTime.UtcNow;

            var model = new DashboardViewModel
            {
                ActiveServers = servers.Count(s => (now - s.LastSeen).TotalSeconds <= 120),
                OfflineServers = servers.Count(s => (now - s.LastSeen).TotalSeconds > 120),

                //TODO: anwendbar, wenn Container implementiert wurden.
                //RunningContainers = containers.Count(c => (now - c.LastSeen).TotalSeconds <= 120),
                //FailedContainers = containers.Count(c => (now - c.LastSeen).TotalSeconds > 120),

                LastLogin = DateTime.Now
            };

            return PartialView("_DashboardStats", model);
        }

    }
}
