using System.Diagnostics.CodeAnalysis;
using Humanizer;
using Markdig;
using Microsoft.EntityFrameworkCore;
using OliverBooth.Common.Data.Web;
using OliverBooth.Common.Services;
using OliverBooth.Data.Web;
namespace OliverBooth.Services;
///
/// Represents a service for interacting with projects.
///
internal sealed class ProjectService : IProjectService
{
private readonly IDbContextFactory _dbContextFactory;
private readonly MarkdownPipeline _markdownPipeline;
///
/// Initializes a new instance of the class.
///
/// The database context factory.
/// The Markdown pipeline.
public ProjectService(IDbContextFactory dbContextFactory, MarkdownPipeline markdownPipeline)
{
_dbContextFactory = dbContextFactory;
_markdownPipeline = markdownPipeline;
}
///
public string GetDescription(IProject project)
{
return Markdig.Markdown.ToHtml(project.Description, _markdownPipeline);
}
///
public IReadOnlyList GetAllProjects()
{
using WebContext context = _dbContextFactory.CreateDbContext();
return context.Projects.OrderBy(p => p.Rank).ThenBy(p => p.Name).ToArray();
}
///
public IReadOnlyList GetProgrammingLanguages(IProject project)
{
using WebContext context = _dbContextFactory.CreateDbContext();
return project.Languages
.Select(l => context.ProgrammingLanguages.Find(l) ?? new ProgrammingLanguage { Name = l.Titleize() })
.ToArray();
}
///
public IReadOnlyList GetProjects(ProjectStatus status = ProjectStatus.Ongoing)
{
using WebContext context = _dbContextFactory.CreateDbContext();
return context.Projects.Where(p => p.Status == status).OrderBy(p => p.Rank).ThenBy(p => p.Name).ToArray();
}
///
public bool TryGetProject(Guid id, [NotNullWhen(true)] out IProject? project)
{
using WebContext context = _dbContextFactory.CreateDbContext();
project = context.Projects.Find(id);
return project is not null;
}
///
public bool TryGetProject(string slug, [NotNullWhen(true)] out IProject? project)
{
using WebContext context = _dbContextFactory.CreateDbContext();
project = context.Projects.FirstOrDefault(p => p.Slug == slug);
return project is not null;
}
}