using Insight.Web.Constants;
using Microsoft.AspNetCore.Components;
using MudBlazor;

namespace Insight.Web.Components.Containers;

public partial class BaseContainer
{
    [Parameter]
    public string Title { get; set; } = Global.Name;

    [Parameter]
    public List<BreadcrumbItem>? Breadcrumbs { get; set; }

    [Parameter]
    public RenderFragment? BreadcrumbAction { get; set; }

    [Parameter]
    public RenderFragment? Content { get; set; }

    [Parameter]
    public Func<Task>? LoadData { get; set; }

    [Parameter]
    public bool DisableReload { get; set; }


    private bool _loading;
    private bool Loading
    {
        get
        {
            return _loading;
        }
        set
        {
            if (value != _loading)
            {
                _loading = value;
                StateHasChanged();
            }
        }
    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            await OnRefreshAsync();
        }
    }

    private async Task OnRefreshAsync()
    {
        if (LoadData is null || Loading) return;

        Loading = true;
        StateHasChanged();

        //var start = Stopwatch.GetTimestamp();

        await LoadData();

        //var time = Stopwatch.GetElapsedTime(start);

        //if (time <= TimeSpan.FromSeconds(1))
        //{
        //    await Task.Delay(TimeSpan.FromSeconds(1).Subtract(time));
        //}

        Loading = false;
        StateHasChanged();
    }
}