//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// AFXUI auxiliary module for Blazor-application (WASM) | Author: Sergei Y.Kitáev
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Net.Http;
using Microsoft.AspNetCore.Components;
using Newtonsoft.Json;

using CommonHelpers.WASM;
using AFXUI;

namespace BookRegistry.Client {

//**************************************************************************************************
public static class ServiceInvocation {
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
static HttpClient HTTP => Services.HttpClient;
//==================================================================================================

/// <exception cref="UEscapeException" />
public static Task<ServiceInvocationResult<R>> ESC_Invoke_A<R>( string requestUri )
where R: GeneralApiResponse =>
   ESC_Invoke_A<R>( requestUri, null );

/// <exception cref="UEscapeException" />
public static async Task<ServiceInvocationResult<R>> ESC_Invoke_A<R>( string requestUri,
                                                                      [HOptional]
                                                                      object? argumentsObj )
where R: GeneralApiResponse
{
   var cancellation = new CancellationTokenSource();
   var queryTask = argumentsObj != null ?
      HTTP.PostAsJsonAsync( requestUri, argumentsObj, cancellation.Token ) :
      HTTP.GetAsync( requestUri, cancellation.Token );
   UCircuit.SetExclusiveCancellation( cancellation );
   try
   {
      var httpResponse = await queryTask;
      httpResponse.EnsureSuccessStatusCode();
/*
      var jsonString = await httpResponse.Content.ReadAsStringAsync();
      var response = PropertyNNBase.ReturnIgnoreRefChecking(() =>
         JsonConvert.DeserializeObject<R>( jsonString ) );
*/
      var response = await PropertyNNBase.ReturnIgnoreRefChecking_A<R>(() =>
         httpResponse.Content.ReadAsAsync<R>( cancellation.Token ) );
      try {
         JsonConvert.SerializeObject( response.Success ?
            response : new GeneralApiResponse( response ) );
      } catch (Exception e) {
         throw OpFailedExceptionCreator.Create(
            "Error of verificational back-pack of received JSON-object:\n"+
            "{0}", HException.GetErrorMessage(e) );
      }
      if ( response.HasExpectedItemsLack )
         throw new OperationFailedException(
            "Error of received JSON-object veridication:\n"+
            "Response has lack of expected data-items (\"GeneralApiResponse<TItem>\")." );
      return new ServiceInvocationResult<R>( response );
   }
   catch (Exception e)
   {
      return new ServiceInvocationResult<R>( e );
   }
   finally
   {
      UCircuit.ResetExclusiveCancellation();
      cancellation.Dispose();
      if ( UCircuit.IsEscapeRequested )
         throw new UEscapeException( typeof(ServiceInvocation), "ESC_Invoke_A<R>" );
   }
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
} // ServiceInvocation
//**************************************************************************************************

} // BookRegistry.Client
