using Microsoft.AspNetCore.Components;
using MudBlazor;
using MarketData.Service;
using eNavigator.Models;

namespace eNavigator.Pages
{
    public partial class Login
    {
        [Inject]
        private NavigationManager NavigationManager { get; set; } = default!;

        bool isLoggedIn = false;
        string[] errors = { };

        public String User { get; set; }

        public String Password { get; set;}

        public String Status { get; set;} = "Enter credentials then click Submit.";

        public bool IsBusy { get; set; } = false;

        public String BusyMessage { get; set;} = "";

        MudForm loginForm;

        protected override async Task OnInitializedAsync()
        {
          await base.OnInitializedAsync();
          String accessToken = stateContainer.Coalesce<String>(StateStrings.Token, default(String));

          if(default != accessToken)
          {
            isLoggedIn = true;
            User=stateContainer.Coalesce<String>(StateStrings.User, default(String));
            Password=stateContainer.Coalesce<String>(StateStrings.Password, default(String));
            Status="Logged in.";
          }
        }

        private async Task<bool> IsLoggedIn()
        {
          return await Task.FromResult(stateContainer.Has(StateStrings.Token));
 //         return await marketDataServiceClient.IsAuthorized();
        }

        public bool SubmitEnabled
        {
          get
          {
            if(isLoggedIn)
            {
              Console.WriteLine("SubmitEnabled : false");
              return false;
            }
            if(User==default || Password==default)
            {
              Console.WriteLine("SubmitEnabled : false");
              return false;
            }
            Console.WriteLine("SubmitEnabled : true");
            return true;
          }
        }

        private async Task PerformLogin()
        {
          try
          {
            BusyMessage = "Logging you in...";
            IsBusy = true;
            bool result = await marketDataServiceClient.Ping();
            if(!result)
            {
              Console.WriteLine("Ping failed.");
              Status="Cannot reach host.";
              return;
            }
            else
            {
              ServiceResult serviceResult =  await marketDataServiceClient.Login(User, Password);
              isLoggedIn = serviceResult.Success;
              if(serviceResult.Success)
              {
                stateContainer.InsertOrUpdate(StateStrings.Token,serviceResult.ContextSpecificResult as String); 
                stateContainer.InsertOrUpdate(StateStrings.User,User); 
                stateContainer.InsertOrUpdate(StateStrings.Password,Password); 
                Status="Logged in..";
                DisplayToast($"User {User} is logged in. {serviceResult.ElapsedTimeMS}(ms)");
                Console.WriteLine($"Login succeeded.  Token {serviceResult.ContextSpecificResult as String}");
              }
              else 
              {
                Status="Login failed, try again.";
                DisplayToast("Login failed.");
                Console.WriteLine($"Login failed.");
              }
            }
          }
          finally
          {
            IsBusy = false;
          }
        }

        /// <summary>
        /// Login cliked handler.  Should not be able o click this once login has succeeded 
        /// </summary>
        /// <returns></returns>
        private async Task LoginClicked()
        {
          if(!await IsLoggedIn())
          {
            await PerformLogin();
          }
          else
          {
            Console.WriteLine("Already logged in");
          }

          return ;
        }

        private void DisplayToast(String message)
        {
          snackbarService.Add(new MarkupString($"<ul><li>{message}</li></ul>"));
        }
    }
}

