using Hcs.Client.Api.Request.Exception;
using Hcs.Client.Internal;
using Hcs.Service.Async.HouseManagement;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace Hcs.Client.Api.Request.HouseManagement
{
    internal class ImportMeteringDeviceDataRequest(ClientBase client) : HouseManagementRequestBase(client)
    {
        protected override bool CanBeRestarted => false;

        internal async Task<bool> ExecuteAsync(MeteringDeviceFullInformationType meteringDevice, CancellationToken token)
        {
            // http://open-gkh.ru/HouseManagement/importMeteringDeviceDataRequest.html
            var request = new importMeteringDeviceDataRequest
            {
                Id = Constants.SIGNED_XML_ELEMENT_ID,
                version = "11.1.0.8",
                MeteringDevice =
                [
                    new importMeteringDeviceDataRequestMeteringDevice()
                    {
                        TransportGUID = Guid.NewGuid().ToString(),
                        Item = meteringDevice
                    }
                ]
            };

            var result = await SendAndWaitResultAsync(request, async asyncClient =>
            {
                var response = await asyncClient.importMeteringDeviceDataAsync(CreateRequestHeader(), request);
                return response.AckRequest.Ack;
            }, token);

            result.Items.OfType<ErrorMessageType>().ToList().ForEach(error =>
            {
                throw RemoteException.CreateNew(error.ErrorCode, error.Description);
            });

            var importResults = result.Items.OfType<getStateResultImportResult>();
            var commonResults = GetCommonResults(importResults);
            foreach (var commonResult in commonResults)
            {
                if (commonResult.ItemElementName == ItemChoiceType26.importMeteringDevice)
                {
                    return commonResult.Item is getStateResultImportResultCommonResultImportMeteringDevice;
                }
            }

            return false;
        }
    }
}
