using Hcs.ClientNet.Api.Request.Exception;
using Hcs.ClientNet.Internal;
using Hcs.Service.Async.DeviceMetering;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace Hcs.ClientNet.Api.Request.DeviceMetering
{
    internal class ImportMeteringDeviceValuesRequest(ClientBase client) : DeviceMeteringRequestBase(client)
    {
        protected override bool CanBeRestarted => false;

        internal async Task<bool> ExecuteAsync(importMeteringDeviceValuesRequestMeteringDevicesValues values, CancellationToken token)
        {
            // http://open-gkh.ru/DeviceMetering/importMeteringDeviceValuesRequest.html
            var request = new importMeteringDeviceValuesRequest
            {
                Id = Constants.SIGNED_XML_ELEMENT_ID,
                version = "10.0.1.1",
                MeteringDevicesValues = [values]
            };

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

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

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

            return true;
        }
    }
}
