using System.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using PaydayFrontend.Models;
using PaydayFrontend.Services;

namespace PaydayFrontend.Controllers;

public class HomeController : Controller
{
    private readonly ILogger<HomeController> _logger;
    private readonly IUniversityService _universityService;

    public HomeController(ILogger<HomeController> logger, IUniversityService universityService)
    {
        _logger = logger;
        _universityService = universityService;
    }
 
    public async Task<IActionResult> Index(string searchString)
    {
        List<University> universities = await _universityService.GetAllUniversity();

        if (!String.IsNullOrEmpty(searchString))
        {
            universities = universities.Where(s => s.Name!.ToLower().Contains(searchString.ToLower()) || s.FullName!.ToLower().Contains(searchString.ToLower())).ToList();
        }
        
        // Выдача университетов в случайном порядке
        var random = new Random(DateTime.Now.Millisecond);
        universities = universities.OrderBy(x => random.Next()).ToList();

        var answer = new UniversityViewModel(universities, searchString);

        return View(answer);
    }
    
    [Route("Directions")]
    public async Task<IActionResult> Directions(long universityId, string searchString)
    {
        if (universityId == 0)
            return RedirectToAction("Index");
        
        var answer = new UniversityDirectionsViewModel();
        answer.University = await _universityService.GetUniversityById(universityId);
        answer.Directions = await _universityService.GetDirectionsByUniversityId(universityId);
        answer.SearchString = searchString;
        
        if (!String.IsNullOrEmpty(searchString))
        {
            answer.Directions = answer.Directions.Where(s => s.Name!.ToLower().Contains(searchString.ToLower()) || s.Code!.ToLower().Contains(searchString.ToLower())).ToList();
        }

        return View(answer);
    }
    
    [Route("Credits")]
    public IActionResult Credits()
    {
        return View();
    }

    public IActionResult Privacy()
    {
        return View();
    }

    [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
    public IActionResult Error()
    {
        return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
    }
}