@using SpotifyAPI.Web;
@page "/"

<PageTitle>Bind</PageTitle>

<h1>Bind Example</h1>

<p>
    <label>
        Songsuche:
        <input @oninput="Search" @bind-value="SearchText" />
    </label>
    <AuthorizeView>
        <Authorized>
            Authorized User
        </Authorized>
        <NotAuthorized>
            Not authorized user
        </NotAuthorized>
    </AuthorizeView>
    <AuthorizeView Roles="Administrator">
        Youre admin!
    </AuthorizeView>

</p>


<ul>
    @if (Results == null)
    {
        <li><label>Searching...</label></li>
    }
    else
    {
        @foreach (FullTrack trk in Results)
        {
            <li>@trk.Artists.FirstOrDefault()?.Name - @trk.Name</li>
        }
    }
</ul>


@code {

    private string? SearchText { get; set; }

    public List<FullTrack> Results = new();

    SpotifyClient? client;

    CancellationTokenSource? SearchTaskControl;


    protected override async Task OnInitializedAsync()
    {
        var config = SpotifyClientConfig.CreateDefault();
        var request = new ClientCredentialsRequest("bb38548fe2f24ddc98bf3ac4c50cf0d8", "70816eae2d214fa88cc81c45b8fd757b");
        var response = await new OAuthClient(config).RequestToken(request);
        client = new SpotifyClient(config.WithToken(response.AccessToken));
    }

    private async Task Search(ChangeEventArgs e)
    {
        SearchTaskControl?.Cancel();
        SearchTaskControl = new();
        Results.Clear();
        if (client == null || e.Value == null) return;
        string searchtext = (string)e.Value;
        if (searchtext.Length < 2) return;
        Console.Write($"Searching {e.Value}...");
        SearchResponse? results = await client.Search.Item(new SearchRequest(SearchRequest.Types.Track, searchtext) { Market = "de" }, SearchTaskControl.Token);
        if (results == null || results.Tracks.Items == null) return;
        Results.AddRange(results.Tracks.Items);
        Console.WriteLine($"Done (First: {Results.FirstOrDefault()}");
    }

}
