using Blazored.LocalStorage;
using ITVisions.Blazor;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Authorization;
using MiracleListAPI;
using System;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Linq;

namespace Web
{
 public class LoginModel : ComponentBase
 {
  [Inject] public BlazorUtil Util { get; set; }
  [Inject] public NavigationManager NavigationManager { get; set; }
  [Inject] AuthenticationStateProvider mLAuthenticationStateProvider { get; set; } = null;
  [Inject] protected ILocalStorageService localStorage { get; set; } = null;
  [Inject] public MiracleListAPI.MiracleListProxy Proxy { get; set; } = null;

  [CascadingParameter] Task<AuthenticationState> authenticationStateTask { get; set; }

  public string Username { get; set; }
  public string Password { get; set; }
  public string Backend { get; set; }
  public string ErrorMsg { get; set; }
  public List<string> ServerList { get; set; } = new List<string>();

  public LoginModel()
  {
   this.mLAuthenticationStateProvider = mLAuthenticationStateProvider;
  }

  protected override async System.Threading.Tasks.Task OnInitializedAsync()
  {
   Console.WriteLine(nameof(LoginModel) + "." + (nameof(OnInitializedAsync)));
   Console.WriteLine("URI: " + this.NavigationManager.Uri);

   bool isLocalhost = this.NavigationManager.Uri.ToLower().Contains("localhost");
   ServerList = AppSettings.GetBackendURLs(isLocalhost);

   if (this.NavigationManager.Uri.ToLower().Contains("/logout"))
   {
    await ((MLAuthenticationStateProvider)mLAuthenticationStateProvider).Logout();
   }

   if (isLocalhost)
   {
    Backend = AppSettings.DebugURL;
   }
   else
   {
    Backend = AppSettings.LiveURL;
   }

   // gibt es ein LoginInfo vom letzten Besuch im Local Storage? Dann verwende daraus den Benutzernamen
   LoginInfo loginInfo = await localStorage.GetItemAsync<LoginInfo>("LoginInfo");
   if (loginInfo != null)
   {
    Username = loginInfo.Username;
   }
  }

  protected override async Task OnAfterRenderAsync(bool firstRender)
  { }

  protected async Task Login()
  {
   ErrorMsg = "Logging in...";
   Util.Log($"{nameof(LoginModel)}.{nameof(Login)}: {Username}/{Password}/{Backend}");

   // Set the Backend-URL for the Proxy
   MiracleListAPI.MiracleListProxy.BackendUrl = Backend;
   LoginInfo loginInfo = await ((MLAuthenticationStateProvider)mLAuthenticationStateProvider).LogIn(Username, Password, Backend);

   if (loginInfo != null && String.IsNullOrEmpty(loginInfo.Message))
   {
    var u = (await authenticationStateTask).User;

    if (u.Identity.IsAuthenticated)
    {
     ErrorMsg = "";
     this.NavigationManager.NavigateTo("/app");
    }
    else
    {
     ErrorMsg = "Unknown Login Error!";
    }
   }
   else
   {
    ErrorMsg = "Login Error: " + loginInfo?.Message;
   }
  }
 } // end class Login
}