using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using MultipleChoiceTrainer.Data;
using MultipleChoiceTrainer.Models;

namespace MultipleChoiceTrainer.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        private readonly SignInManager<IdentityUser> signInManager;
        private readonly ApplicationDbContext context;

        public HomeController(ILogger<HomeController> logger, SignInManager<IdentityUser> signInManager, ApplicationDbContext context)
        {
            _logger = logger;
            this.signInManager = signInManager;
            this.context = context;
        }

        public IActionResult Index(int? categoryId)
        {
            if (signInManager.IsSignedIn(User))
            {
                var categories = context.Categories.Include(e => e.Sections).ThenInclude(e => e.Questions).ToList();
                var selectedCategory = categoryId ?? (categories.FirstOrDefault()?.Id);
                return View(new HomeViewModel() { Categories = categories, SelectedCategoryId = selectedCategory });
            }
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            _logger.Log(LogLevel.Error, "Es ist ein Fehler aufgetreten");
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}
