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

namespace Database.Repository
{
    public class SaleRepository
    {
        public SaleEntity New(int employeeId)
        {
            using PosDbContext context = new PosDbContext();
            SaleEntity saleEntity = new SaleEntity();
            saleEntity.Time = DateTime.Now;
            saleEntity.EmployeeId = employeeId;
            saleEntity.IsModified = true;
            context.Sales.Add(saleEntity);
            context.SaveChanges();
            return saleEntity;
        }

        public SaleLineEntity SaveSaleLine(SaleLineEntity entity)
        {
            using PosDbContext context = new PosDbContext();
            context.SalesLines.Add(entity);
            context.SaveChanges();
            return entity;
        }

        public List<SaleLineEntity> GetSaleLineBySaleId(int saleId)
        {
            using PosDbContext context = new PosDbContext();
            List<SaleLineEntity> saleLineEntities = context.SalesLines.Where(c => c.SaleId == saleId).ToList();
            return saleLineEntities;
        }

        public PaymentEntity SavePayment(PaymentEntity entity)
        {
            using PosDbContext context = new PosDbContext();
            context.Payment.Add(entity);
            context.SaveChanges();
            return entity;
        }

        public List<PaymentEntity> GetPaymentBySaleId(int saleId)
        {
            using PosDbContext context = new PosDbContext();
            List<PaymentEntity> paymentEntities = context.Payment.Where(c => c.SaleId == saleId).ToList();
            return paymentEntities;
        }

        public SaleEntity GetLatest()
        {
            using PosDbContext context = new PosDbContext();
            SaleEntity saleEntity = context.Sales.OrderByDescending(c => c.Id).Take(1).First();
            return saleEntity;
        }

        public SaleEntity Get(int id)
        {
            using PosDbContext context = new PosDbContext();
            SaleEntity saleEntity = context.Sales.Single(c => c.Id == id);
            return saleEntity;
        }

        public List<SaleEntity> GetByDateRange(DateTime start, DateTime end)
        {
            using PosDbContext context = new PosDbContext();
            List<SaleEntity> saleEntities = context.Sales.Where(c => c.Time.Date >= start.Date && c.Time.Date <= end.Date).OrderByDescending(c => c.Time).ToList();
            return saleEntities;
        }

        public List<SaleEntity> GetByDateRange(DateTime start)
        {
            using PosDbContext context = new PosDbContext();
            List<SaleEntity> saleEntities = context.Sales.Where(c => c.Time.Date == start.Date.Date).OrderByDescending(c => c.Time).ToList();
            return saleEntities;
        }

    }
}
