using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Net.Http;
using System.Diagnostics;
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 HomePage: APageComponent {
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
static HomeService SRV => Services.HomeService;
//==================================================================================================
//protected ElementReference? ;
#nullable disable
protected ADropDownList_IdName AuthorDDL,CategoryDDL,GenreDDL, PublisherDDL,SeriesDDL;
protected ADropDownList BookOrderDDL;
protected AEditBox BookNamePartEdit,ISBNPartEdit;
protected AResetControl BookNamePartReset,ISBNPartReset;
protected AButton ResetButton,SelectBooksButton;
protected AUpResetControl BookOrderUpReset;
protected BookInfo BookInfo;
protected BookCard BookCard;
#nullable restore
//==================================================================================================
bool ResetSelectEnabled;
List<SelectBooks_Item>? BookList;
GetBookSelectionCollections_Response? BookSelectionCollections;
//--------------------------------------------------------------------------------------------------

bool HasRequisiteLists =>
   BookSelectionCollections != null;

bool DisplayBookInfo => CurrentSubpage == SubpageType.BookInfo;
bool DisplayBookCard => CurrentSubpage == SubpageType.BookCard;

ElementReference? InitialFocus => BookNamePartEdit.MainElement;

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

SubpageType CurrentSubpage;
SelectBooks_Item? CurrentBook,CurrentListBook;

/// <exception cref="InvalidOperationException" />
SelectBooks_Item CurrentBookNN =>
   CurrentBook ?? throw new InvalidOperationException(
      "\"CurrentBook\"-property is null (\"HomePage\")." );
/// <exception cref="InvalidOperationException" />
SelectBooks_Item CurrentListBookNN =>
   CurrentListBook ?? throw new InvalidOperationException(
      "\"CurrentListBook\"-property is null (\"HomePage\")." );

/// <exception cref="InvalidOperationException" />
List<SelectBooks_Item> BookListNN =>
   BookList ?? throw new InvalidOperationException(
      "\"BookList\"-property is null (\"HomePage\")." );

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

public bool IsOnMainContent => CurrentSubpage == SubpageType.MainContent;
public bool IsOnBookCardSubpage => CurrentSubpage == SubpageType.BookCard;
public bool IsOnBookInfoSubpage => CurrentSubpage == SubpageType.BookInfo;

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

public static bool IsOnSelectionSubPage
{
   get {
      var homePage = App.CurrentPage as HomePage;
      return homePage!=null && homePage.IsOnMainContent;
   }
}

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

internal bool IsForCorrection => Session.IsOpen;
internal bool IsForReadOnly => !IsForCorrection;

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

internal void SwitchToMainContent() =>
   SwitchToSubpage( 0, null );
internal void SwitchToMainContent(BookListCorrection correction)
{
   if ( correction == 0 )
   {
      SwitchToMainContent();
      return;
   }
   var bookList = BookListNN;
   var currentBook = CurrentBookNN;
   var currentListBook = CurrentListBookNN;
   int itemIdx = bookList.FindIndex(item => item==currentListBook);
   if ( itemIdx < 0 )
      throw HAssertion.FAIL( "The book is not found in the list." );
   switch ( correction )
   {
   case BookListCorrection.ApplyEditChange:
      currentBook.corrected = true;
      bookList[ itemIdx ] = currentBook;
      break;
   case BookListCorrection.ApplyRemoval:
      bookList[ itemIdx ].deleted = true;
      break;
   default:
      throw HAssertionFailure.DEAD_BRANCH();
   }
   SwitchToMainContent();
}
internal void SwitchToBookCardSubpage_Adding() =>
   SwitchToSubpage( SubpageType.BookCard, new SelectBooks_Item() );
internal void SwitchToBookCardSubpage_Edit() =>
   SwitchToSubpage( SubpageType.BookCard, CurrentBook );

internal void SwitchToBookInfoSubpage(SelectBooks_Item currentListBook) =>
   SwitchToSubpage( SubpageType.BookInfo,
      (CurrentListBook = currentListBook).SelectBooks_DuplicateItem() );

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

void SwitchToSubpage( SubpageType subpageType,
                      SelectBooks_Item? currentBook )
{
   var lastSubpageType =  HOps.Exchange( ref _LastSubpageType_, subpageType );
   if ( subpageType != 0 && lastSubpageType == 0 )
      UPage.SaveScrolling();
   CurrentSubpage = subpageType;
   CurrentBook = currentBook;
   StateHasChanged();
   MainLayout.Update();
   if ( subpageType == 0 )
   {
      CurrentListBook = null;
      UPage.RestoreScrolling();
   }
   UPage.ClearSelection();
}

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

void ResetBookList()
{
   BookList = null;
   StateHasChanged();
}

//==================================================================================================
/*
protected override void OnInitialized() =>
go(()=>{
   base.OnInitialized();
});
*/
protected override void On_Load() =>
go(()=>{
   HomeMI.ApplyToUI();
   Page_Prepare();
   BookNamePartReset.Target = BookNamePartEdit;
   ISBNPartReset.Target = ISBNPartEdit;
   BookOrderUpReset.Target = BookOrderDDL;
   UnlockOnLoad = false;
});

protected override Task On_AfterLoad_A() =>
Do_A(-1,async()=>{using (new ForeOperation()){
//-- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
   CompletePageLoadingUnlock();
   var sir = await SRV.ESC_GetBookSelectionCollections_A();
   if ( WasAbandoned_Notify_Deactivate( sir ) )
      return;
   if ( sir.HasError )
   {
      await ESC_ShowRequestError_A( sir );
      AuthorDDL         .Clear();
      CategoryDDL       .Clear();
      GenreDDL          .Clear();
      PublisherDDL      .Clear();
      SeriesDDL         .Clear();
      BookNamePartEdit  .Clear();
      ISBNPartEdit      .Clear();
      return;
   }
   var rsp = sir.ResponseNN;
   AuthorDDL   .SetItems( rsp.Authors );
   CategoryDDL .SetItems( rsp.Categories );
   GenreDDL    .SetItems( rsp.Genres );
   PublisherDDL.SetItems( rsp.Publishers );
   SeriesDDL   .SetItems( rsp.Series );
   BookSelectionCollections = rsp;
   EnableButtons();
   StateHasChanged();
   InitialFocus.DeferredFocus();
//-- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
}});

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

void RequisiteList_OnSelectIndex() =>
go(()=>{
   EnableButtons();
});
void RequisiteEdit_OnSetText() =>
go(()=>{
   EnableButtons();
});
void EnableButtons()
{
   bool enable =
      AuthorDDL         .IsSelected ||
      CategoryDDL       .IsSelected ||
      GenreDDL          .IsSelected ||
      PublisherDDL      .IsSelected ||
      SeriesDDL         .IsSelected ||
      BookNamePartEdit  .HasText ||
      ISBNPartEdit      .HasText;
   if ( enable != ResetSelectEnabled )
   {
      ResetSelectEnabled = enable;
      StateHasChanged();
   }
}

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

void AddNewBookBUTTON_OnClick() =>
GO(()=>{
   SwitchToBookCardSubpage_Adding();
});

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

void ResetRequisitesButton_OnClick() =>
GO(()=>{
   AuthorDDL         .Reset();
   CategoryDDL       .Reset();
   GenreDDL          .Reset();
   PublisherDDL      .Reset();
   SeriesDDL         .Reset();
   BookNamePartEdit  .Clear();
   ISBNPartEdit      .Clear();
   InitialFocus.Focus();
});

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

Task RequisiteEdit_OnKeyDown_A(AEditBox editBox,KeyboardEventArgs e) =>
GO(async()=>{
   if ( !UInput.IsPureEnterKey( e ) )
      return;
   if ( SelectBooksButton.Enabled )
   {
      await SelectBooks_A();
      editBox.Select();
   }
   else
      ResetBookList();
});

void SelectBooksButton_OnClick_A() =>
GO(async()=>{ // exclusive method
   await SelectBooks_A();
});

void BookOrderDDL_OnSelectIndex_A() =>
GO(async()=>{ // exclusive method
   if ( BookOrderDDL.IsSelected && SelectBooksButton.Enabled )
      await SelectBooks_A();
   else
      ResetBookList();
});

Task SelectBooks_A() =>
go(async()=>{using (new ForeOperation()){ // non-exclusive method
//-- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
   var args = new SelectBooks_Input()
   {
      NamePart = BookNamePartEdit.Text,
      ISBNPart = ISBNPartEdit.Text,
      AuthorId = AuthorDDL.SelectedId,
      CategoryId = CategoryDDL.SelectedId,
      GenreId = GenreDDL.SelectedId,
      PublisherId = PublisherDDL.SelectedId,
      SeriesId = SeriesDDL.SelectedId,
      //ReleaseYear_From =,
      //ReleaseYear_To =,
      SortingKey = (BookOrderDDL.SelectedItem as BookSortingInfo)?.Key.ToString()
   };
   var sir = await SRV.ESC_SelectBooks_A( args ); // this may throw UEscapeException
   if ( WasAbandoned_Notify_Deactivate( sir ) )
      return;
   if ( await ESC_HasRequestError_ShowError_A( sir ) ) // this may throw UEscapeException
   {
      //BookList = null;
      return;
   }
   BookList = sir.ResponseNN.Items;
   UPage.ClearSelectionDeferredUnscroll();
//-- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
}});

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

SubpageType _LastSubpageType_;

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
} // HomePage
//**************************************************************************************************

} // BookRegistry.Client.Pages
