@page "/admin/users/sessions"

@using Moonlight.Core.UI.Components.Navigations
@using Moonlight.Core.Services
@using MoonCore.Helpers
@using MoonCoreUI.Services
@using Moonlight.Core.Models

@inject SessionService SessionService
@inject AlertService AlertService
@inject ToastService ToastService

@attribute [RequirePermission(1000)]

@implements IDisposable

<AdminUsersNavigation Index="1"/>

<LazyLoader Load="Load">
    <Tooltip>
        This list shows you every user connected to this moonlight instance. Its updated in realtime
    </Tooltip>

    <div class="card mt-5">
        <div class="card-body">
            <LazyLoader Load="Load">
                <CrudTable @ref="Table"
                           TItem="Session"
                           Items="SessionService.Sessions"
                           PageSize="50">
                    <CrudColumn TItem="Session" Title="User" Field="@(x => x.CreatedAt)">
                        <Template>
                            @if (context.IdentityService.IsLoggedIn)
                            {
                                <a target="_blank" href="/admin/users/view/@(context.IdentityService.CurrentUser.Id)">
                                    @(context.IdentityService.CurrentUser.Email)
                                </a>
                            }
                            else
                            {
                                <span>Guest</span>
                            }
                        </Template>
                    </CrudColumn>
                    <CrudColumn TItem="Session" Title="URL" Field="@(x => x.CreatedAt)">
                        <Template>
                            <a target="_blank" href="@(context.NavigationManager.Uri)">
                                @(context.NavigationManager.Uri)
                            </a>
                        </Template>
                    </CrudColumn>
                    <CrudColumn TItem="Session" Title="Last activity" Field="@(x => x.UpdatedAt)" Filterable="true">
                        <Template>
                            <span>@(Formatter.FormatUptime(DateTime.UtcNow - context.UpdatedAt))</span>
                        </Template>
                    </CrudColumn>
                    <CrudColumn TItem="Session" Title="Connected since" Field="@(x => x.CreatedAt)" Filterable="true">
                        <Template>
                            <span>@(Formatter.FormatUptime(DateTime.UtcNow - context.CreatedAt))</span>
                        </Template>
                    </CrudColumn>
                    <CrudColumn TItem="Session" Title="Actions">
                        <Template>
                            <div class="d-flex justify-content-end">
                                <div class="btn btn-group">
                                    <WButton OnClick="() => Message(context)" Text="Message" CssClasses="btn btn-primary" />
                                    <WButton OnClick="() => Redirect(context)" Text="Redirect" CssClasses="btn btn-warning" />
                                </div>
                            </div>
                        </Template>
                    </CrudColumn>
                </CrudTable>
            </LazyLoader>
        </div>
    </div>
</LazyLoader>

@code
{
    private CrudTable<Session>? Table;
    private Timer? UpdateTimer;

    private Task Load(LazyLoader _)
    {
        UpdateTimer = new Timer(async _ =>
        {
            if (Table != null)
                await Table.Refresh();

            await InvokeAsync(StateHasChanged);
        }, null, TimeSpan.Zero, TimeSpan.FromSeconds(1));

        return Task.CompletedTask;
    }

    private async Task Redirect(Session session)
    {
        var url = await AlertService.Text("Enter the target url to redirect to");
        
        if(string.IsNullOrEmpty(url))
            return;
        
        try
        {
            session.NavigationManager.NavigateTo(url);

            await ToastService.Success("Successfully redirected user session");
        }
        catch (Exception)
        {
            await ToastService.Danger("Unable to redirect user. The user is probably no longer connect with moonlight");
        }
    }
    
    private async Task Message(Session session)
    {
        var message = await AlertService.Text("Enter the message you want to send");
        
        if(string.IsNullOrEmpty(message))
            return;
        
        try
        {
            await session.AlertService.Info(message);

            await ToastService.Success("Successfully sent message to user session");
        }
        catch (Exception)
        {
            await ToastService.Danger("Unable to send message. The user is probably no longer connect with moonlight");
        }
    }

    public void Dispose()
    {
        if (UpdateTimer != null)
            UpdateTimer.Dispose();
    }
}