@page "/access_keys"
@inject DedupClient Client;
@inject Blazored.LocalStorage.ILocalStorageService localStorage;
@inject IJSRuntime jsRt;
    
    
@if(Ready)
{
   @foreach(var item in Items)
   {
    
           
     
     
          
      
@item.DeviceName
      
    
    
      
       
    }
}
@code {
    public List Items {get;set;}=new List();
    public bool Ready {get;set;}=false;
    string token="";
    public async Task LogoutAsync()
    {
        if(!await jsRt.InvokeAsync("confirm","Are you sure you want to to logout?")) return;
        
        try{
            await Client.LogoutAsync(token);
        }catch(Exception ex)
        {
            Console.WriteLine(ex);
            _=ex;
        }
        try{
            await localStorage.RemoveItemAsync("token");
            Items.Clear();
            StateHasChanged();
        }catch(Exception ex)
        {
            _=ex;
        }
    }
    public async Task DeleteAsync(AccessKey ak)
    {
        if(!await jsRt.InvokeAsync("confirm",$"Are you sure you want to delete the access key {ak.DeviceName} created {ak.Created.Humanize()}?")) return;
        
        var res=await Client.AccessKeyDeleteAsync(token,ak.Id);
        
        if(res.Success)
        {
            Items.Remove(ak);
            StateHasChanged();
        }
        else
        {
            //error
        }
    }
    protected override async Task OnInitializedAsync()
    {
        var _token = await localStorage.GetItemAsStringAsync("token");
        if(!string.IsNullOrWhiteSpace(_token))
        {
            token = _token;
            Items.Clear();
            try{
            await foreach(var item in Client.GetAccessKeysAsync(_token))
            {
                Items.Add(item);
            }
            }catch(Exception ex){_=ex;}
            Ready=true;
        }
    }
}