using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VentaUniformes.Application.Interfaces;
using VentaUniformes.Application.Persistencia.Producto.Queries.GetAllProduct;
using VentaUniformes.Domain.Entities.Sale;

namespace VentaUniformes.Application.VentasView
{
    public class VentasViewService: IVentasViewService
    {
        IPersistenciaService _persistenciaService;
        IMapper _mapper;
        public VentasViewService(IPersistenciaService persistenciaService, IMapper mapper)
        {
            _persistenciaService = persistenciaService;
            _mapper = mapper;
        }

        public async Task<bool> BorraVenta(int idSale)
        {
            return await _persistenciaService.DeleteSale(idSale);
        }

        public async Task<VentasViewModel> GetNewVenta()
        {
            VentasViewModel res = new VentasViewModel();
            res.Alumno = "";
            res.Curso = "";
            res.ModoPago = 0;
           
            var l = await _persistenciaService.GetAllProduct();
            res.Productos = _mapper.Map<List<LineVentasViewModel>>(l);
            return res;
        }

        public async Task<bool> Save(VentasViewModel model)
        {
            var venta = new SaleEntity();
            venta.Alumno=model.Alumno;
            venta.Curso = model.Curso;
            venta.Fecha =  DateTime.Now;
            venta.PaymentType = model.ModoPago;
            venta.Total = 0;
            foreach (var l in model.Productos)
            {
                venta.Total += (l.Price * l.Cantidad);
            }


                var idsale =await _persistenciaService.AddSale(venta);
            if(idsale<0)
                return false;

            if(model.isBill)
            {
                var bill=new SaleBillEntity();
                bill.Name=model.Name;
                bill.DNI = model.DNI;   
                bill.SaleId=idsale;
                if(!await _persistenciaService.AddSaleBill(bill))
                    return false;
            }
            var lines = new List<SaleLineEntity>();
            foreach (var l in model.Productos)
            {
                if (l.Cantidad > 0)
                {
                    var line = new SaleLineEntity();
                    line.SaleId = idsale;
                    line.ProductId = l.Id;
                    line.Price = (float)l.Price;
                    line.Amount = l.Cantidad;
                    lines.Add(line);
                }

            }


            return await _persistenciaService.AddLineSales(lines);

        }
    }
}
