using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using isnd.Data;
using isnd.ViewModels;
using isnd.Helpers;
using isnd.Interfaces;

namespace isnd
{
    [AllowAnonymous]
    public class PackageVersionController : Controller
    {
        private readonly ApplicationDbContext _context;
        private readonly IPackageManager _pm;

        public PackageVersionController(ApplicationDbContext context,
            IPackageManager pm)
        {
            _context = context;
            _pm = pm;
        }

        // GET: PackageVersion
        public async Task<IActionResult> Index(PackageVersionIndexViewModel model)
        {
            var applicationDbContext = _context.PackageVersions.Include(p => p.Package)
            .Include(p => p.Package.Owner)
            .Include(p => p.Package.Versions)
            .Where(
                p => (model.Prerelease || !p.IsPrerelease)
            && ((model.PackageId == null) || p.PackageId.StartsWith(model.PackageId)));
            model.Versions = await applicationDbContext.ToArrayAsync();
            return View(model);
        }

        [Authorize]
        public async Task<IActionResult> Mines(PackageVersionIndexViewModel model)
        {
            var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
            var applicationDbContext = _context.PackageVersions
                .Include(p => p.Package).Where(
                p => (string.IsNullOrEmpty(model.PackageId) || p.PackageId.StartsWith(model.PackageId))
                && p.Package.OwnerId == userId);

            model.Versions = await applicationDbContext.ToArrayAsync();

            return View("Index", model);
        }
    }
}
