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 ExportSupplyResourceContractDataRequest(ClientBase client) : HouseManagementRequestBase(client)
    {
        protected override bool EnableMinimalResponseWaitDelay => false;

        internal async Task<IEnumerable<exportSupplyResourceContractResultType>> ExecuteAsync(CancellationToken token)
        {
            var result = new List<exportSupplyResourceContractResultType>();

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

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

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

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

                exportContractRootGuid = data.NextGuid;
            }

            return result;
        }

        internal async Task<exportSupplyResourceContractResultType> ExecuteAsync(Guid contractRootGuid, CancellationToken token)
        {
            exportSupplyResourceContractResultType result = null;

            void OnResultReceived(exportSupplyResourceContractResultType[] contracts)
            {
                result = contracts?.Length > 0 ? contracts[0] : null;
            }

            await QueryBatchAsync(contractRootGuid, null, null, OnResultReceived, token);

            return result;
        }

        internal async Task<exportSupplyResourceContractResultType> ExecuteAsync(string contractNumber, CancellationToken token)
        {
            exportSupplyResourceContractResultType result = null;

            void OnResultReceived(exportSupplyResourceContractResultType[] contracts)
            {
                result = contracts?.Length > 0 ? contracts[0] : null;
            }

            await QueryBatchAsync(null, contractNumber, null, OnResultReceived, token);

            return result;
        }

        private async Task<PaginationData> QueryBatchAsync(
            Guid? contractRootGuid, string contractNumber, Guid? exportContractRootGuid,
            Action<exportSupplyResourceContractResultType[]> onResultReceived,
            CancellationToken token)
        {
            var itemsElementName = new List<ItemsChoiceType32>();
            var items = new List<object>();

            if (contractRootGuid.HasValue)
            {
                itemsElementName.Add(ItemsChoiceType32.ContractRootGUID);
                items.Add(contractRootGuid.ToString());
            }

            if (!string.IsNullOrEmpty(contractNumber))
            {
                itemsElementName.Add(ItemsChoiceType32.ContractNumber);
                items.Add(contractNumber);
            }

            if (exportContractRootGuid.HasValue)
            {
                itemsElementName.Add(ItemsChoiceType32.ExportContractRootGUID);
                items.Add(exportContractRootGuid.ToString());
            }

            // http://open-gkh.ru/HouseManagement/exportSupplyResourceContractRequest.html
            var request = new exportSupplyResourceContractRequest
            {
                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.exportSupplyResourceContractDataAsync(
                        CreateRequestHeader(), request);
                    return ackResponse.AckRequest.Ack;
                }, token);

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

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