@page "/"
@attribute [Authorize]
@using CommunityToolkit.Mvvm.Messaging
@using salesbook.Shared.Core.Interface
@using salesbook.Shared.Components.Layout.Spinner
@using salesbook.Shared.Core.Interface.System.Network
@using salesbook.Shared.Core.Interface.System.Notification
@using salesbook.Shared.Core.Messages.Notification.Loaded
@using salesbook.Shared.Core.Services
@inject IFormFactor FormFactor
@inject INetworkService NetworkService
@inject IFirebaseNotificationService FirebaseNotificationService
@inject IShinyNotificationManager NotificationManager
@inject INotificationService NotificationService
@inject PreloadService PreloadService
@inject IMessenger Messenger

<SpinnerLayout FullScreen="true"/>

@code
{
    protected override async Task OnInitializedAsync()
    {
        var lastSyncDate = LocalStorage.Get<DateTime>("last-sync");
        var syncAllData = lastSyncDate.Equals(DateTime.MinValue) || (DateTime.Now - lastSyncDate).TotalDays >= 7;
        var syncCodJcom = lastSyncDate.Day != DateTime.Now.Day;
        
        if (!FormFactor.IsWeb() && NetworkService.ConnectionAvailable && syncAllData)
        {
            var returnPath = System.Web.HttpUtility.UrlEncode("/");
            NavigationManager.NavigateTo($"/sync?path={returnPath}");
            return;
        }

        if (syncCodJcom && !syncAllData)
        {
            var returnPath = System.Web.HttpUtility.UrlEncode("/");
            NavigationManager.NavigateTo($"/sync/{DateTime.Today:yyyy-MM-dd}?path={returnPath}");
            return;
        }

        NetworkService.ConnectionAvailable = NetworkService.IsNetworkAvailable();

        await LoadNotification();
        await CheckAndRequestPermissions();

        try
        {
            await FirebaseNotificationService.InitFirebase();
        }
        catch (Exception e)
        {
            Console.WriteLine($"Firebase init: {e.Message}");
        }

        _ = StartSyncUser();
        NavigationManager.NavigateTo("/Calendar");
    }

    private async Task LoadNotification()
    {
        await NotificationService.LoadNotification();
        Messenger.Send(new NotificationsLoadedMessage());
    }

    private async Task CheckAndRequestPermissions()
    {
        await NotificationManager.RequestAccess();
    }

    private Task StartSyncUser()
    {
        return Task.Run(() => { _ = PreloadService.PreloadUsersAsync(); });
    }
}
