

using System.Collections.Generic;
using System.Linq;
using Database.Models;

namespace Database.Repository
{
    public class ProductRepository
    {
        public List<ProductEntity> GetAll()
        {
            using PosDbContext context = new PosDbContext();
            List<ProductEntity> products = context.Products
                .Where(c => c.IsArchived == false)
                .OrderBy(c => c.Index)
                .ToList();
            return products;
        }

        public List<ProductEntity> GetByProductGroup(int id)
        {
            using PosDbContext context = new PosDbContext();
            List<ProductEntity> products = context.Products
                .Where(c => c.ProductGroupId == id)
                .Where(c => c.IsArchived == false)
                .OrderBy(c => c.Index)
                .ToList();
            return products;
        }

        public void SetIndex(int id, int index)
        {
            using PosDbContext context = new PosDbContext();
            ProductEntity product = context.Products.Single(c => c.Id == id);
            product.Index = index;
            product.IsModified = true;
            context.SaveChanges();
        }

        public ProductEntity GetById(int id)
        {
            using PosDbContext context = new PosDbContext();
            ProductEntity product = context.Products.Single(c => c.Id == id);
            return product;
        }

        public void Update(int id, int productGroupId, string name)
        {
            using PosDbContext context = new PosDbContext();
            ProductEntity dbProduct = context.Products.Single(c => c.Id == id);
            dbProduct.ProductGroupId = productGroupId;
            dbProduct.Name = name;
            dbProduct.IsModified = true;
            context.SaveChanges();
        }

        public void Archive(int id)
        {
            using PosDbContext context = new PosDbContext();
            ProductEntity dbProduct = context.Products.Single(c => c.Id == id);
            dbProduct.IsArchived = true;
            dbProduct.IsModified = true;
            context.SaveChanges();
        }

        public void Add(string name, int productGroupId)
        {

            ProductEntity product = new ProductEntity();
            product.Name = name;
            product.ProductGroupId = productGroupId;
            using PosDbContext context = new PosDbContext();
            //Get the highest index
            ProductEntity highest = context.Products.OrderByDescending(c => c.Index).Take(1).FirstOrDefault();
            if (highest == null)
            {
                highest = new ProductEntity();
                highest.Index = 0;
            }
            product.Index = highest.Index + 1;
            product.IsModified = true;
            context.Products.Add(product);
            context.SaveChanges();
        }
    }
}
