using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Forms;
using Microsoft.AspNetCore.Components.Routing;
using Microsoft.AspNetCore.Components.Web;

using CommonHelpers.WASM;
using AFXUI;

using BookRegistry.Client.Shared;
using BookRegistry.Client.Components;
using BookRegistry.Client.DB;

namespace BookRegistry.Client.Pages {

//**************************************************************************************************
public partial class AuthorizationPage: APageComponent {
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
static UserAuthorizationService SRV => Services.UserAuthorizationService;
static ServiceUser_Info USR => Session.UserInfo;
//==================================================================================================
#nullable disable
protected AEditBox UserNameEdit, PasswordEdit;
protected AResetControl ResetControl_UserName, ResetControl_Password;
protected AErrorList ErrorList;
protected AButton SubmitButton;
#nullable restore
bool IsSubmissionEnabled;
//==================================================================================================

MarkupString ColumnTD =>
   (MarkupString)"<td><span class=\"faint_bold_text\">:<span>&nbsp;</td>";

//--------------------------------------------------------------------------------------------------

const string
   KnownUser_1 = "user1", Password_1 = "12345",
   KnownUser_2 = "user2", Password_2 = "67890",
   KnownUser_3 = "$pushkin", Password_3 = "qwerty",
   KnownUser_4 = "$lermont", Password_4 = "asdfgh";

string KnownUserHRef_1 => $"#{KnownUser_1}";
string KnownUserHRef_2 => $"#{KnownUser_2}";
string KnownUserHRef_3 => $"#{KnownUser_3}";
string KnownUserHRef_4 => $"#{KnownUser_4}";
string KnownUserInsertTitle_1 => $"Insert: \"{KnownUser_1}\", \"{Password_1}\"";
string KnownUserInsertTitle_2 => $"Insert: \"{KnownUser_2}\", \"{Password_2}\"";
string KnownUserInsertTitle_3 => $"Insert: \"{KnownUser_3}\", \"{Password_3}\"";
string KnownUserInsertTitle_4 => $"Insert: \"{KnownUser_4}\", \"{Password_4}\"";

//==================================================================================================
/*
protected override void OnInitialized() =>
go(()=>{
   base.OnInitialized();
});
*/
protected override void On_Load() =>
go(()=>{
   AuthorizationMI.ApplyToUI();
   Page_Prepare();
   if ( !Session.IsOpen )
   {
/*
      UserNameEdit.Text = KnownUser_1;
      PasswordEdit.Text = Password_1;
*/
      ResetControl_UserName.Target = UserNameEdit;
      ResetControl_Password.Target = PasswordEdit;
      AggregateInputError_EnableSubmission();
   }
});
protected override void On_AutoFocus()
{
   if ( !Session.IsOpen )
      UserNameEdit.DeferredFocus();
}

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

string? UserName_Validate(string text)
{
   if ( text == "" )
      return "User name is empty.";
   if ( text.Contains(' ') )
      return "User name must not contain spaces.";
   if ( text.Length > DBConstants.LoginNameCapacity )
      return "User name is too long.";
   return null;
}
string? Password_Validate(string text)
{
   if ( text == "" )
      return "Password field is empty.";
   if ( text.Contains(' ') )
      return "Password must not contain spaces.";
   if ( text.Length > DBConstants.UserPasswordMaxLength )
      return "Password is too long.";
   return null;
}

bool ValidateInput()
{
   UserNameEdit.ValidateInput();
   PasswordEdit.ValidateInput();
   return AggregateInputError_EnableSubmission();
}
bool AggregateInputError_EnableSubmission()
{
   var list = new List<string>();
   string? msg = UserNameEdit.ErrorMessage;
   if ( msg != null )
      list.Add( msg );
   msg = PasswordEdit.ErrorMessage;
   if ( msg != null )
      list.Add( msg );
   EnableSubmission();
   return ErrorList.SetErrorMessages( list );
}

bool EnableSubmission()
{
   bool enableSubmission =
      !UserNameEdit.HasError && !PasswordEdit.HasError &&
      UserName_Validate( UserNameEdit.Text ) == null &&
      Password_Validate( PasswordEdit.Text ) == null;
   if ( enableSubmission != IsSubmissionEnabled )
   {
      IsSubmissionEnabled = enableSubmission;
      StateHasChanged();
   }
   return enableSubmission;
}

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

void KnownUserA_OnClick(string userName,string password) =>
go(()=>{
   UserNameEdit.Text = userName;
   PasswordEdit.Text = password;
   ValidateInput();
   UserNameEdit.Focus();
});

void EditBox_OnInput() =>
go(()=>{
   AggregateInputError_EnableSubmission();
});

void EditBox_OnKeyDown(KeyboardEventArgs e) =>
go(()=>{
   if ( e.Key=="Enter" && !UInput.HasKeyModifiers( e ) )
      SubmitButton.Click();
});

void SubmitButton_OnClick_A() =>
GO(async()=>{using (new ForeOperation()){
//-- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ValidateInput();
if ( ErrorList.HasErrors )
{
   await ESC_ShowError_A( "Input error", ErrorList.AggregatedMessageNN );
   if ( UserNameEdit.HasError )
      UserNameEdit.Focus();
   else if ( PasswordEdit.HasError )
      PasswordEdit.Focus();
   else
      SubmitButton.Focus();
   return;
}
//-- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
using (new SaveFocus())
{
   var sir = await SRV.ESC_AuthorizeUser_A( UserNameEdit.Text, PasswordEdit.Text );
   if ( WasAbandoned_Notify_Deactivate( sir ) )
      return;
   if ( await ESC_HasRequestError_ShowError_A( sir ) )
      return;
   var rsp = sir.ResponseNN;
   var localTime = DateTime.Now;
/*
// Local date-time obtainment under Mono (before .NET 5):
   var localTime = DateTime.UtcNow -
      TimeSpan.FromMinutes( JS.Invoke<int>( "DateTime_TimezoneOffset" ) );
*/
   Session.Open( rsp.UserInfo, rsp.RoleName, localTime );
   NAV.NavigateTo( "/" );
} // SaveFocus
//-- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
}});

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
} // AuthorizationPage
//**************************************************************************************************

} // BookRegistry.Client.Pages
