using AutoMapper;
using AutoMapper.QueryableExtensions;
using CleanArchitecture.Application.Common.Interfaces;
using CleanArchitecture.Application.Common.Security;
using MediatR;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using CleanArchitecture.Application.Common.Mappings;
using CleanArchitecture.Application.TodoItems.Queries.GetTodoItemsWithPagination;
using CleanArchitecture.Domain.Entities;
using CleanArchitecture.WebUI.Controllers;
using Microsoft.AspNetCore.Mvc;
namespace CleanArchitecture.Application.TodoLists.Queries.GetTodos
{
[Authorize]
public class GetTodosController : ApiControllerBase
{
[HttpGet]
public async Task<ActionResult<TodosVm>> Get()
{
return await Mediator.Send(new GetTodosQuery());
}
}
public class GetTodosQuery : IRequest<TodosVm>
{
}
public class TodosVm
{
public IList<PriorityLevelDto> PriorityLevels { get; set; }
public IList<TodoListDto> Lists { get; set; }
}
public class TodoListDto : IMapFrom<TodoList>
{
public TodoListDto()
{
Items = new List<TodoItemDto>();
}
public int Id { get; set; }
public string Title { get; set; }
public string Colour { get; set; }
public IList<TodoItemDto> Items { get; set; }
}
public class PriorityLevelDto
{
public int Value { get; set; }
public string Name { get; set; }
}
public class GetTodosQueryHandler : IRequestHandler<GetTodosQuery, TodosVm>
{
private readonly IApplicationDbContext _context;
private readonly IMapper _mapper;
public GetTodosQueryHandler(IApplicationDbContext context, IMapper mapper)
{
_context = context;
_mapper = mapper;
}
public async Task<TodosVm> Handle(GetTodosQuery request, CancellationToken cancellationToken)
{
return new TodosVm
{
PriorityLevels = Enum.GetValues(typeof(PriorityLevel))
.Cast<PriorityLevel>()
.Select(p => new PriorityLevelDto { Value = (int)p, Name = p.ToString() })
.ToList(),
Lists = await _context.TodoLists
.AsNoTracking()
.ProjectTo<TodoListDto>(_mapper.ConfigurationProvider)
.OrderBy(t => t.Title)
.ToListAsync(cancellationToken)
};
}
}
}