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

namespace WorkFlowCheck.MAUI.Services
{
    public class SyncService : BaseService, ISyncService
    {
        private readonly IUserService _userService;
        public SyncService(HttpClient httpClient, IConfiguration configuration, AppDbContext dbContext, IMapper mapper, IUserService userService) : base(httpClient, configuration, dbContext, mapper)
        {
            _userService = userService;
        }
        public async Task SyncDatas()
        {
            await SyncCheckPointsDown();
            await SyncLocations();
            await SyncEquipments();
            await SyncCheckListTemplates();
            await SyncCheckList();
        }
        public async Task SyncCheckPointsDown()
        {
            try
            {
                await PrepareAuthenticatedRequestAsync();
                // Az API végpont meghatározása
                string endpoint = $"{_httpClient.BaseAddress}api/Sync/GetAllCheckPoints";

                // HTTP GET kérés küldése
                var response = await _httpClient.GetFromJsonAsync<ApiResponseDTO<List<CheckPointDTO>>>(endpoint);
                if (response != null)
                {
                    if (response.IsSuccess)
                    {
                        var entityList = await _dbContext.CheckPoints.ToListAsync();
                        var missingItems = response.Data.Where(f => !entityList.Any(s => s.Id == f.Id)).ToList();

                        var mappedMissingItems = _mapper.Map<List<CheckPoint>>(missingItems);

                        _dbContext.CheckPoints.AddRange(mappedMissingItems);
                        await _dbContext.SaveChangesAsync();
                    }
                }
            }
            catch (Exception ex)
            {
                // Hiba visszaadása

            }
        }
        public async Task SyncCheckPointsUp()
        {
            try
            {
                await PrepareAuthenticatedRequestAsync();
                // Az API végpont meghatározása
                string endpoint = $"{_httpClient.BaseAddress}api/Sync/GetAllCheckPoints";
                // HTTP GET kérés küldése
                var response = await _httpClient.GetFromJsonAsync<ApiResponseDTO<List<CheckPointDTO>>>(endpoint);
                if (response != null)
                {
                    if (response.IsSuccess)
                    {
                        var entityList = await _dbContext.CheckPoints.ToListAsync();
                        var missingItems = response.Data.Where(f => !entityList.Any(s => s.Id == f.Id & s.Code == f.Code)).ToList();



                        var checkPointListDTO = _mapper.Map<List<CheckPointDTO>>(missingItems);

                        foreach (var item in checkPointListDTO)
                        {
                            var entity = await _dbContext.CheckPoints.Where(w => w.Id == item.Id).FirstOrDefaultAsync();
                            if (entity != null)
                            {
                                item.ShortName = entity.ShortName;
                                item.Code = entity.Code;
                            }
                        }

                        endpoint = $"{_httpClient.BaseAddress}api/Sync/UpdateAllCheckPoint";
                        using (HttpResponseMessage httpResponseMessage = await _httpClient.PostAsJsonAsync(endpoint, checkPointListDTO))
                        {
                            httpResponseMessage.EnsureSuccessStatusCode();
                            var jsonString = await httpResponseMessage.Content.ReadAsStringAsync();
                            response = JsonConvert.DeserializeObject<ApiResponseDTO<List<CheckPointDTO>>>(jsonString);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                // Hiba visszaadása
            }
        }

        public async Task SyncLocations()
        {
            try
            {
                await PrepareAuthenticatedRequestAsync();
                // Az API végpont meghatározása
                string endpoint = $"{_httpClient.BaseAddress}api/Sync/GetAllLocations";

                // HTTP GET kérés küldése
                var response = await _httpClient.GetFromJsonAsync<ApiResponseDTO<List<LocationDTO>>>(endpoint);
                if (response != null)
                {
                    if (response.IsSuccess)
                    {
                        var entityList = await _dbContext.Locations.ToListAsync();
                        var missingItems = response.Data.Where(f => !entityList.Any(s => s.Id == f.Id)).ToList();

                        var mappedMissingItems = _mapper.Map<List<Location>>(missingItems);

                        _dbContext.Locations.AddRange(mappedMissingItems);
                        await _dbContext.SaveChangesAsync();
                    }
                }
            }
            catch (Exception ex)
            {
                // Hiba visszaadása

            }
        }
        public async Task SyncEquipments()
        {
            try
            {
                await PrepareAuthenticatedRequestAsync();
                // Az API végpont meghatározása
                string endpoint = $"{_httpClient.BaseAddress}api/Sync/GetAllEquipments";

                // HTTP GET kérés küldése
                var response = await _httpClient.GetFromJsonAsync<ApiResponseDTO<List<EquipmentDTO>>>(endpoint);
                if (response != null)
                {
                    if (response.IsSuccess)
                    {
                        var entityList = await _dbContext.Locations.ToListAsync();
                        var missingItems = response.Data.Where(f => !entityList.Any(s => s.Id == f.Id)).ToList();

                        var mappedMissingItems = _mapper.Map<List<Equipment>>(missingItems);

                        _dbContext.Equipments.AddRange(mappedMissingItems);
                        await _dbContext.SaveChangesAsync();
                    }
                }
            }
            catch (Exception ex)
            {
                // Hiba visszaadása

            }
        }
        public async Task SyncCheckListTemplates()
        {
            try
            {
                await PrepareAuthenticatedRequestAsync();
                // Az API végpont meghatározása
                var userId = _userService.GetCurrentUser()?.Id;
                string endpoint = $"{_httpClient.BaseAddress}api/Sync/GetAllCheckListTemplateHeader/{userId}";

                // HTTP GET kérés küldése
                var response = await _httpClient.GetFromJsonAsync<ApiResponseDTO<List<CheckListTemplateHeaderDTO>>>(endpoint);
                if (response != null)
                {
                    if (response.IsSuccess)
                    {
                        var checkListTemplateHeaderList = await _dbContext.CheckListTemplateHeaders.ToListAsync();
                        var missingItems = response.Data.Where(f => !checkListTemplateHeaderList.Any(s => s.Id == f.Id)).ToList();

                        var missingCheckListTemplateHeaders = _mapper.Map<List<CheckListTemplateHeader>>(missingItems);

                        _dbContext.CheckListTemplateHeaders.AddRange(missingCheckListTemplateHeaders);
                        await _dbContext.SaveChangesAsync();
                    }
                }
            }
            catch (Exception ex)
            {
                // Hiba visszaadása

            }
        }
        public async Task SyncCheckList()
        {
            try
            {
                await PrepareAuthenticatedRequestAsync();
                if (_userService == null)
                {
                    return;
                }
                // Az API végpont meghatározása
                var userId = _userService.GetCurrentUser()?.Id;
                string endpoint = $"{_httpClient.BaseAddress}api/Sync/GetAllCheckListHeader/{userId}";

                // HTTP GET kérés küldése

                var response = await _httpClient.GetFromJsonAsync<ApiResponseDTO<List<CheckListHeaderDTO>>>(endpoint);
                if (response != null)
                {
                    if (response.IsSuccess)
                    {
                        var checkListHeaderList = await _dbContext.CheckListHeaders.ToListAsync();
                        var missingItems = response.Data.Where(f => !checkListHeaderList.Any(s => s.GuidNumber == f.GuidNumber)).ToList();

                        var missingCheckListHeaders = _mapper.Map<List<CheckListHeader>>(missingItems);

                        _dbContext.CheckListHeaders.AddRange(missingCheckListHeaders);
                        await _dbContext.SaveChangesAsync();

                        foreach (var item in missingItems)
                        {
                            var checkListHeaderDTO = item as CheckListHeaderDTO;

                            foreach (var checkListRowDTO in checkListHeaderDTO.CheckListRowDTO)
                            {
                                var checkListRow = _dbContext.CheckListRows.Where(w => w.GuidNumber == checkListRowDTO.GuidNumber).FirstOrDefault();
                                var isAdd = false;
                                if (checkListRow == null)
                                {
                                    isAdd = true;
                                    checkListRow = new CheckListRow();
                                    checkListRow.CheckListHeaderId = checkListHeaderDTO.Id;
                                }
                                checkListRow.Answer = checkListRowDTO.Answer;
                                checkListRow.CheckListTemplateRowId = checkListRowDTO.CheckListTemplateRowId;
                                checkListRow.GuidNumber = checkListRowDTO.GuidNumber;
                                checkListRow.Photo = checkListRowDTO.Photo;

                                if (isAdd) _dbContext.CheckListRows.Add(checkListRow);
                                await _dbContext.SaveChangesAsync();
                            }
                        }
                    }

                }
            }
            catch (Exception ex)
            {
                // Hiba visszaadása

            }
        }
    }
}
