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

namespace Hcs.Client.Api.Request.HouseManagement
{
    internal class ExportSupplyResourceContractObjectAddressDataRequest(ClientBase client) : HouseManagementRequestBase(client)
    {
        internal async Task<IEnumerable<exportSupplyResourceContractObjectAddressResultType>> ExecuteAsync(Guid contractRootGuid, CancellationToken token)
        {
            var result = new List<exportSupplyResourceContractObjectAddressResultType>();

            void OnResultReceived(exportSupplyResourceContractObjectAddressResultType[] addresses)
            {
                if (addresses?.Length > 0)
                {
                    result.AddRange(addresses);
                }
            }

            var pageNum = 0;
            Guid? exportObjectGuid = null;
            while (true)
            {
                pageNum++;

                client.TryLog($"Querying page #{pageNum}...");

                var data = await QueryBatchAsync(contractRootGuid, exportObjectGuid, OnResultReceived, token);
                if (data.IsLastPage)
                {
                    break;
                }

                exportObjectGuid = data.NextGuid;
            }

            return result;
        }

        private async Task<PaginationData> QueryBatchAsync(
            Guid contractRootGuid, Guid? exportObjectGuid,
            Action<exportSupplyResourceContractObjectAddressResultType[]> onResultReceived,
            CancellationToken token)
        {
            var itemsElementName = new List<ItemsChoiceType34>();
            var items = new List<string>();

            itemsElementName.Add(ItemsChoiceType34.ContractRootGUID);
            items.Add(contractRootGuid.ToString());

            if (exportObjectGuid.HasValue)
            {
                itemsElementName.Add(ItemsChoiceType34.ExportObjectGUID);
                items.Add(exportObjectGuid.ToString());
            }

            // http://open-gkh.ru/HouseManagement/exportSupplyResourceContractObjectAddressRequest.html
            var request = new exportSupplyResourceContractObjectAddressRequest
            {
                Id = Constants.SIGNED_XML_ELEMENT_ID,
                version = "13.1.1.1",
                ItemsElementName = [.. itemsElementName],
                Items = [.. items]
            };

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

                var contractResult = result.Items.OfType<getStateResultExportSupplyResourceContractObjectAddress>().First();
                onResultReceived?.Invoke(contractResult.ObjectAddress);

                return new PaginationData(contractResult.Item);
            }
            catch (NoResultsRemoteException)
            {
                return PaginationData.CreateLastPageData();
            }
            catch (System.Exception e)
            {
                throw e;
            }
        }
    }
}
