@page "/sync"
@page "/sync/{DateFilter}"
@using salesbook.Shared.Components.Layout.Spinner
@using salesbook.Shared.Components.SingleElements
@using salesbook.Shared.Core.Interface
@inject ISyncDbService SyncDb
@inject IManageDataService ManageData

<SyncSpinner Elements="@Elements"/>

<AppVersion/>

@code {
    [Parameter] public string? DateFilter { get; set; }

    private Dictionary<string, bool> Elements { get; set; } = new();

    private bool _hasStarted;
    private int _completedCount;

    protected override void OnInitialized()
    {
        Elements["Commesse"] = false;

        if (DateFilter is null)
            Elements["Impostazioni"] = false;
    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender && !_hasStarted)
        {
            _hasStarted = true;

            if (DateFilter is null)
                await ManageData.ClearDb();

            await Task.WhenAll(
                RunAndTrack(SetCommesse),
                RunAndTrack(SetSettings)
            );
        }
    }

    private async Task RunAndTrack(Func<Task> func)
    {
        await func();

        _completedCount++;
        if (_completedCount == Elements.Count)
        {
            LocalStorage.Set("last-sync", DateTime.Now);

            var pathQuery = System.Web.HttpUtility.ParseQueryString(new UriBuilder(NavigationManager.Uri).Query);
            var originalPath = pathQuery["path"] ?? null;
            var path = originalPath ?? "/Calendar";

            NavigationManager.NavigateTo(path, replace: true);
        }
    }

    private async Task SetCommesse()
    {
        await Task.Run(async () => { await SyncDb.GetAndSaveCommesse(DateFilter); });

        Elements["Commesse"] = true;
        StateHasChanged();
    }

    private async Task SetSettings()
    {
        if (DateFilter is null)
        {
            await Task.Run(async () => { await SyncDb.GetAndSaveSettings(DateFilter); });

            Elements["Impostazioni"] = true;
            StateHasChanged();
        }
    }

}