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

<SyncSpinner Elements="@Elements"/>

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

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

    private bool _hasStarted = false;
    private int _completedCount = 0;

    protected override void OnInitialized()
    {
        Elements["Attività"] = false;
        Elements["Commesse"] = false;
        Elements["Clienti"] = false;
        Elements["Prospect"] = false;
        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(SetActivity),
                RunAndTrack(SetClienti),
                RunAndTrack(SetProspect),
                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 SetActivity()
    {
        await Task.Run(async () => { await syncDb.GetAndSaveActivity(DateFilter); });

        Elements["Attività"] = true;
        StateHasChanged();
    }

    private async Task SetClienti()
    {
        await Task.Run(async () => { await syncDb.GetAndSaveClienti(DateFilter); });

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

    private async Task SetProspect()
    {
        await Task.Run(async () => { await syncDb.GetAndSaveProspect(DateFilter); });

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

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

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

    private async Task SetSettings()
    {
        await Task.Run(async () => { await syncDb.GetAndSaveSettings(DateFilter); });

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

}