using ITVisions.Blazor;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Hosting;
using System;
using System.Threading.Tasks;

namespace Web.Pages
{
 public partial class Login
 {
  [Inject]
  public BlazorUtil Util { get; set; }

  [Inject]
  public NavigationManager NavigationManager { get; set; }

  [Inject]
  AuthenticationStateProvider mLAuthenticationStateProvider { get; set; } = null;

  [Inject]
  IWebHostEnvironment Env { get; set; } = null;


  public string Username { get; set; }
  public string Password { get; set; }
  string Backend { get; set; }
  string ErrorMsg { get; set; }

  protected override async System.Threading.Tasks.Task OnInitializedAsync()
  {
   Util.Log(nameof(Login) + "." + (nameof(OnInitializedAsync)) + " ENV: " + Env.EnvironmentName);

   if (Env.EnvironmentName == "Development")
   {
    Username = AppSettings.DebugUser; // nur zum einfacheren Debugging
    Password = AppSettings.DebugPassword; // nur zum einfacheren Debugging
   }
   Backend = DAL.Context.ConnectionString;
   if (this.NavigationManager.Uri.ToLower().Contains("/logout"))
   {
    ((MLAuthenticationStateProvider)mLAuthenticationStateProvider).Logout();
   }
  }

  protected async Task DoLogin()
  {
   Util.Log($"{nameof(Login)}.{nameof(DoLogin)}: {Username}");

   BO.User u = await ((MLAuthenticationStateProvider)mLAuthenticationStateProvider).LogIn(Username, Password, Backend);
   if (u != null)
   {
    Util.Log($"{nameof(Login)}.{nameof(DoLogin)}: OK!");
    this.NavigationManager.NavigateTo("/app");
   }
   else
   {
    Util.Log($"{nameof(Login)}.{nameof(DoLogin)}: Login Error!");
    ErrorMsg = "Login Error!";
   }
  }
 }
}