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

namespace Hcs.ClientNet.Api.Request.HouseManagement
{
    internal class ImportContractDataRequest(ClientBase client) : HouseManagementRequestBase(client)
    {
        protected override bool CanBeRestarted => false;
        internal async Task<importContractResultType> ExecuteAsync(ImportContractDataPayload payload, CancellationToken token)
        {
            // TODO: Добавить проверку пейлоада

            // http://open-gkh.ru/HouseManagement/importContractRequest/Contract.html
            var contract = new importContractRequestContract
            {
                TransportGUID = Guid.NewGuid().ToString(),
                Item = GetContractFromPayload(payload)
            };

            // http://open-gkh.ru/HouseManagement/importContractRequest.html
            var request = new importContractRequest
            {
                Id = Constants.SIGNED_XML_ELEMENT_ID,
                version = "11.9.0.1",
                Contract = [contract]
            };

            var result = await SendAndWaitResultAsync(request, async asyncClient =>
            {
                var response = await asyncClient.importContractDataAsync(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.importContract)
                {
                    if (commonResult.Item is importContractResultType importedContract)
                    {
                        return importedContract;
                    }
                }
            }

            return null;
        }

        private importContractRequestContractPlacingContract GetContractFromPayload(ImportContractDataPayload payload)
        {
            // http://open-gkh.ru/HouseManagement/importContractRequest/Contract/PlacingContract.html
            var contract = new importContractRequestContractPlacingContract()
            {
                ContractObject = payload.contractObjects,
                DocNum = payload.docNum,
                SigningDate = payload.signingDate,
                EffectiveDate = payload.effectiveDate,
                PlanDateComptetion = payload.planDateComptetion,
                Item = true,
                ItemElementName = ItemChoiceType13.Owners,
                ContractBase = new nsiRef()
                {
                    Code = payload.contractBase.Code,
                    GUID = payload.contractBase.GUID
                },
                DateDetails = payload.dateDetailsType,
                ContractAttachment = payload.contractAttachment
            };

            return contract;
        }
    }
}
