using System.Linq;
using System.Threading.Tasks;
using isnd.ViewModels;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace isnd.Controllers
{

    public partial class PackagesController
    {

        // GET: PackageVersion
        public async Task<IActionResult> Index(PackageIndexViewModel model)
        {
            var applicationDbContext = _dbContext.Packages.Include(p => p.Versions).Where(
                p => (  model.Prerelease || p.Versions.Any(v => !v.IsPrerelease))
            && ((model.Query == null) || p.Id.StartsWith(model.Query)));
            model.Data = await applicationDbContext.ToArrayAsync();
            return View(model);
        }
        
        public async Task<IActionResult> Details(string pkgid)
        {
            if (pkgid == null)
            {
                return NotFound();
            }

            var packageVersion = _dbContext.PackageVersions
                .Include(p => p.Package)
                .Where(m => m.PackageId == pkgid)
                .OrderByDescending(p => p)
                ;

            if (packageVersion == null)
            {
                return NotFound();
            }
            bool results = await packageVersion.AnyAsync();
            var latest = await packageVersion.FirstAsync();

            return View("Details", new PackageDetailViewModel
            {
                latest = latest,
                pkgid = pkgid,
                totalHits = packageVersion.Count(),
                data = packageVersion.Take(10).ToArray()
            });

        }
    }

}