using AutoMapper;
using Microsoft.EntityFrameworkCore;
using Serilog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WorkFlowCheck.BL.Services.Interfaces;
using WorkFlowCheck.Common.DTO;
using WorkFlowCheck.DL;
using WorkFlowCheck.DL.Entities;

namespace WorkFlowCheck.BL.Services
{
    public class CheckListService : ICheckListService
    {
        private AppDbContext _dbContext;
        private IMapper _mapper;

        public CheckListService(AppDbContext dbContext, IMapper mapper)
        {
            _dbContext = dbContext;
            _mapper = mapper;
        }
        public async Task<CheckListHeaderDTO> GetCheckListHeaderAsync(int Id)
        {
            var retVal = new CheckListHeaderDTO()
            {
                CheckListRowDTO = new List<CheckListRowDTO>()
            };

            try
            {
                var res = await _dbContext.CheckListHeaders
                                       .Where(w => w.Id == Id)
                                       .Include(i => i.CheckListRows)
                                       .AsNoTracking()
                                       .FirstOrDefaultAsync();

                if (res != null)
                {
                    retVal = _mapper.Map<CheckListHeaderDTO>(res);

                }
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);
            }

            return retVal;
        }
        public async Task<CheckListHeaderDTO> StartNewCheckListAsync(ApiRequestDTO<CheckListTemplateHeaderDTO> request)
        {
            var retVal = new CheckListHeaderDTO()
            {
                CheckListRowDTO = new List<CheckListRowDTO>()
            };

            try
            {
                var currentDate = DateTime.UtcNow;
                CheckListHeader checkListHeader = new CheckListHeader()
                {
                    CheckListTemplateHeaderId = request.Data.Id,
                    CreatedAt = currentDate,
                    CreatedBy = request.UserDTO.UserName,
                    Description = request.Data.Description,
                    DocumentNumber = "",
                    GuidNumber = Guid.NewGuid(),
                    IsDeleted = false,
                    IsStorno = false,
                    LastModAt = currentDate,
                    ShortName = "",
                    CheckListRows = new List<CheckListRow>()
                };
                _dbContext.CheckListHeaders.Add(checkListHeader);
                await _dbContext.SaveChangesAsync();

                retVal = _mapper.Map<CheckListHeaderDTO>(checkListHeader);
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);
            }
            return retVal;
        }
    }
}
