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

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

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

        // Daten der Backgroundchecks abrufen
        private IDashboardStore _dashboardStore;

        // System Store für Konfigurationen
        private ISystemStore _systemStore;

        // HomeController Constructor
        public HomeController(AppDbContext context, ILogger<HomeController> logger, IDashboardStore dashboardStore, ISystemStore systemStore)
        {
            _context = context;
            _logger = logger;
            _dashboardStore = dashboardStore;
            _systemStore = systemStore;

        }

        // Dashboard unter /home/index
        [HttpGet("/")]
        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,
                Servers = await _context.Servers
                    .OrderBy(s => s.Name)
                    .ToListAsync(),
                RecentEvents = await _context.LogEvents
                    .OrderByDescending(e => e.Timestamp)
                    .Take(20)
                    .ToListAsync(),
                Containers = await _context.Containers
                    .OrderBy(s => s.Name)
                    .ToListAsync(),
                NetworkStatus = _dashboardStore.NetworkStatus,
                DatabaseStatus = _dashboardStore.DatabaseStatus,
                RefreshIntervalMilliseconds = _systemStore.FrontendRefreshIntervalMilliseconds
            };
            //ViewBag.NetworkConnection = _NetworkCheckStore.NetworkStatus;
            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 async Task<IActionResult> DashboardStats()
        {
            var servers = _context.Servers.ToList();
            var containers = _context.Containers.ToList();

            var now = DateTime.UtcNow;

            var model = 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),
                Servers = await _context.Servers
                    .OrderBy(s => s.Name)
                    .ToListAsync(),
                RecentEvents = await _context.LogEvents
                    .OrderByDescending(e => e.Timestamp)
                    .Take(20)
                    .ToListAsync(),
                Containers = await _context.Containers
                    .OrderBy(s => s.Name)
                    .ToListAsync(),
                NetworkStatus = _dashboardStore.NetworkStatus,
                DatabaseStatus = _dashboardStore.DatabaseStatus
            };

            return PartialView("_DashboardStats", model);
        }

        public string ReturnNetworkStatus()
        {
            return "OK";
        }

    }
}
