Files
webzine/Webzine.WebApplication/Controllers/RechercheController.cs

76 lines
2.7 KiB
C#

using Microsoft.AspNetCore.Mvc;
using Webzine.Repository.Contracts;
using Webzine.WebApplication.ViewModels.Recherche;
using Webzine.WebApplication.ViewModels.Titre;
namespace Webzine.WebApplication.Controllers;
/// <summary>
/// Controleur responsable de la recherche d'artistes et de titres musicaux.
/// </summary>
[Route("recherche")]
public class RechercheController : Controller
{
private readonly ILogger<RechercheController> logger;
private readonly ITitreRepository titreRepository;
/// <summary>
/// Initialise une nouvelle instance de la classe <see cref="RechercheController"/>.
/// </summary>
/// <param name="logger">Service de journalisation injecté pour suivre les opérations du contrôleur.</param>
/// <param name="titreRepository">Repository des titres injecté pour effectuer les recherches d'artistes et de titres.</param>
public RechercheController(ILogger<RechercheController> logger, ITitreRepository titreRepository)
{
this.logger = logger;
this.titreRepository = titreRepository;
}
/// <summary>
/// Affiche les résultats de la recherche d'artistes et de titres en fonction du mot-clé fourni.
/// </summary>
/// <param name="mot">Le mot-clé de recherche utilisé pour trouver les artistes et les titres correspondants.</param>
/// <returns>Une vue contenant les résultats de la recherche d'artistes et de titres.</returns>
[HttpPost("")]
public IActionResult Index(string mot)
{
this.logger.LogInformation("Recherche artistes/titres pour le mot : {Mot}.", mot);
var titres = this.titreRepository.Search(mot)
.Concat(this.titreRepository.SearchByStyle(mot))
.DistinctBy(t => t.IdTitre)
.OrderBy(t => t.Libelle)
.Select(t => new TitreStyleItem
{
IdTitre = t.IdTitre,
Libelle = t.Libelle,
ArtisteNom = t.Artiste?.Nom,
UrlJaquette = t.UrlJaquette,
Duree = t.Duree,
})
.ToList();
var artistes = this.titreRepository.FindAll()
.Select(t => t.Artiste)
.Where(a => !string.IsNullOrWhiteSpace(a.Nom)
&& !string.IsNullOrWhiteSpace(mot)
&& a.Nom.Contains(mot, StringComparison.OrdinalIgnoreCase))
.DistinctBy(a => a!.IdArtiste)
.OrderBy(a => a!.Nom)
.Select(a => new RechercheArtisteItem
{
Nom = a!.Nom,
NombreDeTitres = a.Titres?.Count ?? 0,
})
.ToList();
var vm = new RechercheIndexViewModel
{
Mot = mot,
Artistes = artistes,
Titres = titres,
};
return this.View(vm);
}
}