@page "/PersonalInfo"
@attribute [Authorize]
@using salesbook.Shared.Components.Layout
@using salesbook.Shared.Components.SingleElements
@using salesbook.Shared.Core.Authorization.Enum
@using salesbook.Shared.Core.Interface
@using salesbook.Shared.Core.Interface.System.Network
@using salesbook.Shared.Core.Services
@inject AppAuthenticationStateProvider AuthenticationStateProvider
@inject INetworkService NetworkService
@inject IFormFactor FormFactor

<HeaderLayout BackTo="Indietro" Back="true" BackOnTop="true" Title="Profilo" ShowProfile="false"/>

@if (IsLoggedIn)
{
    <div class="container content pb-safe-area">
        <div class="container-primary-info">
            <div class="section-primary-info">
                <MudAvatar Style="height: 70px; width: 70px; font-size: 2rem; font-weight: bold"
                           Color="Color.Secondary">
                    @UtilityString.ExtractInitials(UserSession.User.Fullname)
                </MudAvatar>

                <div class="personal-info">
                    <span class="info-nome">@UserSession.User.Fullname</span>
                    @if (UserSession.User.KeyGroup is not null)
                    {
                        <span
                            class="info-section">@(((KeyGroupEnum)UserSession.User.KeyGroup).ConvertToHumanReadable())</span>
                    }
                </div>
            </div>

            <div class="divider"></div>

            <div class="section-info">
                <div class="section-personal-info">
                    <div>
                        <span class="info-title">Telefono</span>
                        <span class="info-text">000 0000000</span> @*Todo: to implement*@
                    </div>

                    <div>
                        <span class="info-title">Status</span>
                        @if (NetworkService.ConnectionAvailable)
                        {
                            <div class="status online">
                                <i class="ri-wifi-line"></i>
                                <span>Online</span>
                            </div>
                        }
                        else
                        {
                            <div class="status offline">
                                <i class="ri-wifi-off-line"></i>
                                <span>Offline</span>
                            </div>
                        }
                    </div>
                </div>

                <div class="section-personal-info">
                    <div>
                        <span class="info-title">E-mail</span>
                        <span class="info-text">
                            @if (string.IsNullOrEmpty(UserSession.User.Email))
                            {
                                @("Nessuna mail configurata")
                            }
                            else
                            {
                                @UserSession.User.Email
                            }
                        </span>
                    </div>

                    <div>
                        <span class="info-title">Ultima sincronizzazione</span>
                        <span class="info-text">@LastSync.ToString("g")</span>
                    </div>
                </div>
            </div>
        </div>

        <div class="container-button">
            <MudButton Class="button-settings green-icon"
                       FullWidth="true"
                       StartIcon="@Icons.Material.Outlined.Sync"
                       Size="Size.Medium"
                       OnClick="@(() => UpdateDb())"
                       Variant="Variant.Outlined">
                Sincronizza
            </MudButton>

            @* <div class="divider"></div> *@

            @* <MudButton Class="button-settings red-icon"
                       FullWidth="true"
                       StartIcon="@Icons.Material.Outlined.Sync"
                       Size="Size.Medium"
                       OnClick="() => UpdateDb()"
                       Variant="Variant.Outlined">
                Ripristina dati
            </MudButton> *@
        </div>

        <div class="container-button">
            <MudButton Class="button-settings exit"
                       FullWidth="true"
                       Color="Color.Error"
                       Size="Size.Medium"
                       OnClick="Logout"
                       Variant="Variant.Outlined">
                Esci
            </MudButton>
        </div>
    </div>

    <AppVersion/>
}

@code {
    private bool Unavailable { get; set; }
    private bool IsLoggedIn { get; set; }
    private DateTime LastSync { get; set; }

    protected override async Task OnInitializedAsync()
    {
        IsLoggedIn = await UserSession.IsLoggedIn();
        await LoadData();
    }

    private async Task LoadData()
    {
        await Task.Run(() =>
        {
            Unavailable = FormFactor.IsWeb() || !NetworkService.ConnectionAvailable;
            LastSync = LocalStorage.Get<DateTime>("last-sync");
        });

        StateHasChanged();
    }

    private void OpenSettings() =>
        NavigationManager.NavigateTo("/settings/Profilo");

    private async Task Logout()
    {
        await AuthenticationStateProvider.SignOut();
        IsLoggedIn = await UserSession.IsLoggedIn();
        StateHasChanged();
    }

    private void UpdateDb(bool withData = false)
    {
        LocalStorage.Remove("last-user-sync");
        
        var absoluteUri = NavigationManager.ToAbsoluteUri(NavigationManager.Uri);
        var pathAndQuery = absoluteUri.Segments.Length > 1 ? absoluteUri.PathAndQuery : null;

        string path;

        if (withData)
            path = pathAndQuery == null ? $"/sync/{DateTime.Today:yyyy-MM-dd}" : $"/sync/{DateTime.Today:yyyy-MM-dd}?path=" + System.Web.HttpUtility.UrlEncode(pathAndQuery);
        else
            path = pathAndQuery == null ? "/sync" : "/sync?path=" + System.Web.HttpUtility.UrlEncode(pathAndQuery);

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

}