    using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Database.Models;
using Microsoft.EntityFrameworkCore;

namespace Database.Repository
{
    public class ProductGroupRepository
    {
        public List<ProductGroupEntity> GetAll()
        {
            using PosDbContext context = new PosDbContext();
            List<ProductGroupEntity> productGroups = context.ProductGroups
                .Include(c => c.Products)
                .Where(c => c.IsArchived == false)
                .OrderBy(c => c.Index)
                .ToList();
            return productGroups;
        }

        public ProductGroupEntity Get(int id)
        {
            using PosDbContext context = new PosDbContext();
            ProductGroupEntity product = context.ProductGroups.Single(c => c.Id == id);
            return product;
        }

        public void Add(string name)
        {
            ProductGroupEntity productGroup = new ProductGroupEntity();
            productGroup.Name = name;
            using PosDbContext context = new PosDbContext();
            //Get the highest index
            ProductGroupEntity highest = context.ProductGroups.OrderByDescending(c => c.Index).Take(1).FirstOrDefault();
            if(highest == null)
            {
                highest = new ProductGroupEntity();
                highest.Index = 0;
            }
            productGroup.Index = highest.Index + 1;
            context.ProductGroups.Add(productGroup);
            context.SaveChanges();
        }

        public void Edit(string name, int id)
        {
            using PosDbContext context = new PosDbContext();
            ProductGroupEntity productGroup = context.ProductGroups.Single(c => c.Id == id);
            productGroup.Name = name;
            context.SaveChanges();
        }

        public void Archive(int id)
        {
            using PosDbContext context = new PosDbContext();
            ProductGroupEntity productGroup = context.ProductGroups.Single(c => c.Id == id);
            productGroup.IsArchived = true;
            context.SaveChanges();
        }

        public void SetIndex(int id, int index)
        {
            using PosDbContext context = new PosDbContext();
            ProductGroupEntity productGroup = context.ProductGroups.Single(c => c.Id == id);
            productGroup.Index = index;
            context.SaveChanges();
        }

        public bool Any()
        {
            using PosDbContext context = new PosDbContext();
            bool any = context.ProductGroups.Any();
            return any;
        }
    }
}
