using eNavigator.Routes;
using MarketData.MarketDataModel;
using MarketData.Service;
using MarketData.Utils;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.JSInterop;
using MudBlazor;

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

    [Inject]
    private AuthenticationStateProvider authenticationStateProvider { get; set; } = default; 

    [Inject]
    private IJSRuntime JSRuntime { get; set; } = default;

    public bool IsBusy { get; set; } = false;
    public String BusyMessage { get; set;} = "";   
    public List<Headline> HeadlinesCollection { get; set;}  = new List<Headline>();
    
    public List<DateTime> AvailableDates { get; set;} = new List<DateTime>();

    public DateTime SelectedDate { get; set; } = Utility.Epoch;

    private int selectedRowNumber = -1;
    private MudTable<Headline> mudTable;

    protected override async Task OnInitializedAsync()
    {
      await base.OnInitializedAsync();
      AuthenticationState authenticationState = await authenticationStateProvider.GetAuthenticationStateAsync();
      if(!authenticationState.User.Identity.IsAuthenticated)
      {
          NavigationManager.NavigateTo(PageRoute.Login);
          return;
      }  
      await LoadAvailableHeadlineDates();
      SelectedDate = AvailableDates.Count()>0 ? AvailableDates[0] : SelectedDate;  
      await LoadHeadlines(SelectedDate);
      StateHasChanged();
      Task.Run(async () => await Task.Yield()).GetAwaiter();             
    }

    private async Task OnValueChanged()
    {
      await LoadHeadlines(SelectedDate);
    }    

    private async Task LoadHeadlines(DateTime headlineDate)
    {
      BusyMessage = $"Loading Headlines for {headlineDate.ToShortDateString()}...";
      IsBusy=true;
      ServiceResult serviceResult = await marketDataServiceClient.GetHeadlines(headlineDate); 
      if(!serviceResult.Success)
      {
        DisplayToast("Error contacting server, could not load latest headlines.");
        return;
      }
      HeadlinesCollection = (serviceResult.ContextSpecificResult as List<Headline>);
      DisplayToast($"Loaded {HeadlinesCollection.Count} headlines for {headlineDate.ToShortDateString()} in {Utility.FormatNumber(serviceResult.ElapsedTimeMS,0,true)}(ms).");
      IsBusy = false;
    }

    private async Task LoadAvailableHeadlineDates()
    {
      BusyMessage = "Loading Available Headline Dates...";
      IsBusy=true;
      ServiceResult serviceResult = await marketDataServiceClient.GetHeadlineDates(); 
      IsBusy = false;
      if(!serviceResult.Success)
      {
        DisplayToast("Error contacting server, could not load headline dates.");
        return;
      }
      List<String> availableDates = (serviceResult.ContextSpecificResult as List<String>);
      availableDates = availableDates.Take(30).ToList();
      for(int index=0;index<availableDates.Count();index++)
      {
        Console.WriteLine(availableDates[index]);
      }
      AvailableDates = availableDates.Select(x => DateTime.Parse(x)).ToList();
      IsBusy = false;
      DisplayToast($"Loaded {AvailableDates.Count} headline dates in {Utility.FormatNumber(serviceResult.ElapsedTimeMS,0,true)}(ms).");
    }

    protected void RowClickEvent(TableRowClickEventArgs<Headline> tableRowClickEventArgs)
    {
      JSRuntime.InvokeAsync<string>("open", $"https://www.google.com/search?q="+Uri.EscapeDataString(tableRowClickEventArgs.Item.Entry));
    }    

    protected async Task RefreshClicked()
    {
      SelectedDate = AvailableDates.Count()>0 ? AvailableDates[0] : SelectedDate;  
      await LoadHeadlines(SelectedDate);
      StateHasChanged();
      Task.Run(async () => await Task.Yield()).GetAwaiter();     
    }

    protected string SelectedRowClassFunc(Headline headline, int rowNumber)
    {
        if (selectedRowNumber == rowNumber)
        {
            selectedRowNumber = -1;
            return string.Empty;
        }
        else if (mudTable.SelectedItem != null && mudTable.SelectedItem.Equals(headline))
        {
            selectedRowNumber = rowNumber;
            return "selected";
        }
        else
        {
            return string.Empty;
        }
    }

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