using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Components;
using Microsoft.JSInterop;
using ITVisions.Blazor;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;

namespace Web.Pages
{
 public partial class ServerState
 {
  [Inject] public BlazorUtil Util { get; set; } = null;
  [Inject] public NavigationManager NavigationManager { get; set; } = null;
  [Inject] public MiracleListAPI.MiracleListProxy Proxy { get; set; } = null;

  public Dictionary<string, bool?> BackendStatusList = new Dictionary<string, bool?>();

  public ServerState()
  {  }

  #region Standard-Lebenszyklus-Ereignisse

  protected async override Task OnInitializedAsync()
  {
   bool isLocalhost = this.NavigationManager.Uri.ToLower().Contains("localhost");

   foreach (var url in AppSettings.GetBackendURLs(isLocalhost))
   {
    // Serverstatus: Null = unklar
    // Localhost-URLs nur auf Localhost nutzen
    if (!url.ToLower().Contains("localhost") || isLocalhost) this.BackendStatusList.Add(url, null);
   }
  }

  protected async override Task OnAfterRenderAsync(bool firstRender)
  {
   if (firstRender)
   {
    #region Backend Status im Hintergrund testen
    foreach (var url in BackendStatusList.Keys.ToList())
    {
     _ = Task.Run(async () =>
     {
      this.Proxy.BaseUrl = url;
      try
      {
       Console.WriteLine("Checking Server Status " + url);
       await this.Proxy.AboutAsync();
       this.BackendStatusList[url] = true;
       Console.WriteLine("Server " + url + ": OK!");
      }
      catch (Exception ex)
      {
       this.BackendStatusList[url] = false;
       Console.WriteLine("Server " + url + ": " + ex.Message);
      }
      this.StateHasChanged();
     });
    }
   }
   #endregion
  }

  #endregion

 }
}