﻿@page "/tag/{tag}"
@inject IHttpApiClientRequestBuilderFactory Http;
@inject NavigationManager navigationManager;
@inject IMessageService messageService;
@inject ApiAuthenticationStateProvider ApiAuthenticationStateProvider;
@layout MainLayout

<div class="pure-g toss-list">

    <div class="pure-u-5-5 tag-header">

        <h1>
            #@tag
            <AuthorizeView>
                @if (!context.User.HashTags().Contains(tag))
                {
                    <button @onclick="@AddHashtag" id="BtnAddHashTag">
                        <Icon Title="Add" IconType="plus"></Icon>
                    </button>
                }
                else
                {
                    <button @onclick="@RemoveHashTag">
                        <Icon Title="Remove" IconType="minus"></Icon>
                    </button>
                }
            </AuthorizeView>
            <ConnectedTagsBar Hashtag="@tag"></ConnectedTagsBar>
        </h1>


    </div>

    @if (Tosses.Any())
    {
        foreach (var tossGroup in Tosses)
        {
            <AdToss tag="@tag"></AdToss>
            foreach (var toss in tossGroup)
            {
                <OneToss toss="@toss" />
            }
        }
        if (!LastPage)
        {
            if (!Loading)
            {
                <div class="pure-u-5-5">
                    <div class="message-info page-next" @onclick="@ShowMore">
                        Click here to load more Toss for  #@tag.
                    </div>
                </div>
            }
        }
        else
        {
            <div class="pure-u-5-5">
                <div class="message-warning page-end">
                    This is all we have for #@tag.
                </div>
            </div>
        }
    }
    else if (!Loading)
    {

        <div class="pure-u-5-5">
            <div class="message-warning no-content">
                There is not Toss for #@tag yet :( <br /> It's up to you to start something.
            </div>
        </div>
    }
    @if (Loading)
    {

        <div class="pure-u-5-5">
            <div class="message-info loading">
                Loading
            </div>
        </div>
    }
</div>
@code{
    [Parameter] public string tag { get; set; } = "";

    List<List<TossLastQueryItem>> Tosses = new List<List<TossLastQueryItem>>();

    private string DisplayedTag;

    private bool Loading { get; set; } = false;

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

    protected int Page { get; set; } = 0;

    protected override async Task OnParametersSetAsync()
    {
        if (DisplayedTag != tag)
        {
            await GetTosstag();
        }
    }

    public override async Task SetParametersAsync(ParameterView parameters)
    {

        if (string.IsNullOrEmpty(parameters.GetValueOrDefault<string>("tag")))
        {
            tag = null;
        }

        await base.SetParametersAsync(parameters);
    }
    protected async Task ResettagDisplay()
    {
        ResetDisplayState();
        await GetTosstag();
    }
    private void ResetDisplayState()
    {
        Tosses = new List<List<TossLastQueryItem>>();
        LastPage = false;
        Page = 0;
    }
    protected async Task GetTosstag()
    {
        if (DisplayedTag != tag)
        {
            ResetDisplayState();
        }
        DisplayedTag = tag;
        if (string.IsNullOrWhiteSpace(tag))
        {
            return;//
        }
        Loading = true;
        await Http.Create("/api/toss/last")
            .OnOK<List<TossLastQueryItem>>(l =>
            {
                Tosses.Add(l);
                Loading = false;
                if (l.Count < TossLastQuery.TossPerPage)
                {
                    LastPage = true;
                }
                StateHasChanged();
            })
            .Get(new TossLastQuery(DisplayedTag, Page));
    }

    protected async Task ShowMore()
    {
        Page++;
        await GetTosstag();
    }
    protected async Task AddHashtag(MouseEventArgs ev)
    {
        await Http.Create("/api/account/addHashTag")
            .OnOK(() =>
            {
                ApiAuthenticationStateProvider.RefreshCurrentUser();
                messageService.Info("Hashtag added with success");
            })
            .OnBadRequest<Dictionary<string, List<string>>>(
                e => messageService.Error(string.Join(",", e["newTag"]))
            )
            .Post(new AddHashtagCommand(tag)); 

    }

    protected async Task RemoveHashTag(MouseEventArgs e)
    {
        await Http.Create("/api/account/removeHashTag")
            .OnOK(() =>
            {
                ApiAuthenticationStateProvider.RefreshCurrentUser();
                messageService.Info("Hashtag removed with success");
            })
            .Post(new RemoveHashTagCommand(tag));
    }
}
