using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using System.Net.Http;
using System.Net.Http.Json;
using System.Net.Http.Headers;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Forms;
using Microsoft.AspNetCore.Components.Routing;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.JSInterop;

using CommonHelpers.WASM;
using AFXUI;

using BookRegistry.Client.Shared;
using BookRegistry.Client.Pages;

namespace BookRegistry.Client {

//**************************************************************************************************
partial class App {
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
protected static HttpClient HTTP => Services.HttpClient;
//==================================================================================================

public static AppConfig? Configuration { get; private set; }
public static string? ConfigurationError { get; private set; }

//==================================================================================================

public static async Task<bool> TryLoadConfiguration(bool copyProperties=true)
{
   AppConfig? cfg;
   try
   {
      cfg = await HTTP.GetFromJsonAsync<AppConfig>( "appconfig.json" ) ??
         throw new HUnsuccessException( "Web-server returned null on request of configuration file." );
   }
   catch (Exception e)
   {
      Configuration = null;
      ConfigurationError = HException.GetErrorMessage(e);
      UConsole.PrintError(
         "=== Configuration loading has failed: ===\n"+
         "{0}", ConfigurationError );
      return false;
   }
   Configuration = cfg;
   ConfigurationError = null;
   Console.WriteLine( "App.configuration has been loaded successfully." );
   if ( copyProperties )
   {
      string? language = cfg.Query?.Language;
      QueryLanguage = language;
      Locale = GetAppLocale( language );
      Console.WriteLine( "Query language: {0}", QueryLanguage );
      Console.WriteLine( "App.locale: {0}", Locale );
   }
   return true;
}

//==================================================================================================

static AppLocale GetAppLocale(string? language)
{
   if ( language == null )
      return AppLocale.Neutral;
   switch ( language?.ToUpper() )
   {
   case "EN": return AppLocale.EN;
   case "RU": return AppLocale.RU;
   default: return AppLocale.Neutral;
   } // switch
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
} // App
//**************************************************************************************************

} // BookRegistry.Client
