using AutoMapper;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using System.Net.Http.Json;
using System.Runtime.CompilerServices;
using WorkFlowCheck.Common.DTO;
using WorkFlowCheck.MAUI.DataLayer;
using WorkFlowCheck.MAUI.Services.Interfaces;

namespace WorkFlowCheck.MAUI.Services
{
    public class CheckListService : BaseService, ICheckListService
    {
        private readonly IUserService _userService;
        private readonly ISyncService _syncService;
        public CheckListService(HttpClient httpClient,
                                IConfiguration configuration,
                                AppDbContext dbContext,
                                IMapper mapper,
                                IUserService userService,
                                ISyncService syncService) : base(httpClient, configuration, dbContext, mapper)
        {
            _userService = userService;
            _syncService = syncService;
        }

        public async Task<ApiResponseDTO<CheckPointDTO>> GetCheckPoint(int checkPointId)
        {
            var retVal = new ApiResponseDTO<CheckPointDTO>() { IsSuccess = true };
            try
            {
                var res = await _dbContext.CheckPoints.Include(i => i.CheckListTemplateRows).Where(w => w.Id == checkPointId).FirstOrDefaultAsync();
                retVal.Data = _mapper.Map<CheckPointDTO>(res);
            }
            catch (Exception ex)
            {
                retVal.IsSuccess = false;
                retVal.Errors.Add(ex.Message);
            }
            return retVal;
        }
        public async Task<ApiResponseDTO<CheckPointDTO>> GetCheckPoint(string checkPointCode)
        {
            var retVal = new ApiResponseDTO<CheckPointDTO>() { IsSuccess = true };
            try
            {
                var res = await _dbContext.CheckPoints.Include(i => i.CheckListTemplateRows).Where(w => w.Code == checkPointCode).FirstOrDefaultAsync();
                retVal.Data = _mapper.Map<CheckPointDTO>(res);
            }
            catch (Exception ex)
            {
                retVal.IsSuccess = false;
                retVal.Errors.Add(ex.Message);
            }
            return retVal;
        }

        public async Task<ApiResponseDTO<CheckListHeaderDTO>> StartNew(CheckListHeaderNewDTO checkListHeaderNewDTO)
        {
            try
            {
                await PrepareAuthenticatedRequestAsync();
                // Az API végpont meghatározása
                string endpoint = $"{_httpClient.BaseAddress}api/checklist/StartNewCheckList";

                using (HttpResponseMessage httpResponseMessage = await _httpClient.PostAsJsonAsync(endpoint, checkListHeaderNewDTO))
                {
                    httpResponseMessage.EnsureSuccessStatusCode();

                    var jsonString = await httpResponseMessage.Content.ReadAsStringAsync();
                    var response = JsonConvert.DeserializeObject<ApiResponseDTO<CheckListHeaderDTO>>(jsonString);

                    return response ?? new ApiResponseDTO<CheckListHeaderDTO>
                    {
                        IsSuccess = false,
                    };
                }
            }
            catch (Exception ex)
            {
                // Hiba visszaadása
                return new ApiResponseDTO<CheckListHeaderDTO>
                {
                    IsSuccess = false
                };
            }
        }

        public async Task<List<CheckListHeaderDTO>> GetCheckLists(int userId)
        {
            //await _syncService.SyncDatas();

            var retVal = new List<CheckListHeaderDTO>();
            try
            {
                var res = await _dbContext.CheckListHeaders.ToListAsync();
                retVal = _mapper.Map<List<CheckListHeaderDTO>>(res);
            }
            catch (Exception ex)
            {

            }
            return retVal;
        }

        public async Task<List<CheckListTemplateHeaderDTO>> GetCheckListTemplates(int userId)
        {
            //await _syncService.SyncDatas();

            var retVal = new List<CheckListTemplateHeaderDTO>();
            try
            {
                var res = await _dbContext.CheckListTemplateHeaders.ToListAsync();
                retVal = _mapper.Map<List<CheckListTemplateHeaderDTO>>(res);
            }
            catch (Exception ex)
            {

            }
            return retVal;
        }

        public async Task<List<CheckListRowDTO>> GetCheckListRowsByCheckPointCode(int userId, int checkListHeaderId, string checkPointCode)
        {
            var retVal = new List<CheckListRowDTO>();

            try
            {
                var checkListRows = await _dbContext.CheckListRows
                                            .Include(i => i.CheckListTemplateRow)
                                            .ThenInclude(i => i.CheckPoint)
                                            .Include(i => i.CheckListHeader)
                                            .Where(w => w.CheckListTemplateRow.CheckPoint.Code == checkPointCode &&
                                                        w.CheckListHeader.UserId == userId &&
                                                        w.CheckListHeaderId == checkListHeaderId)
                                            .AsNoTracking()
                                            .ToListAsync();
                retVal = _mapper.Map<List<CheckListRowDTO>>(checkListRows);
            }
            catch (Exception ex)
            {


            }


            return retVal;
        }

        public async Task<CheckListRowDTO> UpdateCheckListRow(CheckListRowDTO checkListRowDTO)
        {
            var retVal = checkListRowDTO;
            try
            {
                var checkListRow = await _dbContext.CheckListRows.Where(w => w.Id == checkListRowDTO.Id).FirstOrDefaultAsync();
                if (checkListRow != null)
                {
                    checkListRow.Answer = checkListRowDTO.Answer;
                    if (checkListRowDTO.Photo != null && checkListRowDTO.Photo.Length > 0)
                    {
                        checkListRow.Photo = checkListRowDTO.Photo;
                    }
                    await _dbContext.SaveChangesAsync();
                }
            }
            catch (Exception)
            {
            }
            return retVal;
        }
    }
}
