using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components;
using Microsoft.JSInterop;
using ITVisions.Blazor;
using Microsoft.AspNetCore.Components.Authorization;
using System.Security.Claims;

namespace Web.Pages
{
 public partial class TaskEdit
 {

  [Parameter]
  public BO.Task Task { get; set; }

  [Parameter] // Ereignis
  public EventCallback<int> TaskHasChanged { get; set; }

  string token = "";

  [Inject]
  BlazorUtil Util { get; set; } = null;

  [Inject]
  MiracleListAPI.MiracleListProxy Proxy { get; set; } = null;

  // Erweiterung https://github.com/BlazorExtensions/Notifications läuft derzeit nicht zuverlässig
  //[Inject] private INotificationService _notificationService { get; set; }

  [CascadingParameter] Task<AuthenticationState> authenticationStateTask { get; set; }

  protected override async System.Threading.Tasks.Task OnInitializedAsync()
  {
   ClaimsPrincipal u = (await authenticationStateTask).User;
   token = (u.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Sid).Value);
   //Console.WriteLine(nameof(TaskEdit) +"." + nameof(OnInitialized) + ": " + Task.TaskID);
   Util.Log(nameof(TaskEdit) + "." + nameof(OnInitialized) + ": " + Task.TaskID);
  }

  // wenn Parameter gesetzt wird
  protected async override void OnParametersSet()
  {
   Util.Log((nameof(OnParametersSet) + ": " + Task.TaskID));
  }

  protected async void Save()
  {
   Util.Log(nameof(Save) + ": " + Task.TaskID);
   Util.Log("Task: " + this.Task);

   try
   {
    // Erweiterung https://github.com/BlazorExtensions/Notifications läuft derzeit nicht zuverlässig
    //bool IsSupportedByBrowser = await _notificationService.IsSupportedByBrowserAsync();
    //if (IsSupportedByBrowser)
    //{
    // PermissionType permission = await _notificationService.RequestPermissionAsync();
    // await _notificationService.CreateAsync("Speichern", "Aufgabe #" + this.task.TaskID + " wurde gespeichert", "assets/MiracleListLogo.png");
    //}
   }
   catch (Exception)
   {

   }

   await AppState.Proxy.ChangeTaskAsync(this.Task, token);
   await TaskHasChanged.InvokeAsync(Task.TaskID);
  }

  protected async void Cancel()
  {
   Util.Log(nameof(Cancel) + ": " + Task.TaskID);
   await GetTask(Task.TaskID);
   await TaskHasChanged.InvokeAsync(Task.TaskID);
  }

  private async Task GetTask(int id)
  {
   Util.Log(nameof(GetTask) + ": " + id);
   this.Task = await AppState.Proxy.TaskAsync(id, token);
   Util.Log(this.Task);
  }
 } // end class TaskEdit
}