@page "/admin/nodes"
@using Moonlight.App.Repositories
@using Moonlight.App.Database.Entities
@using Moonlight.Shared.Components.Navigations
@using Moonlight.App.Services
@using Moonlight.App.Services.Interop
@using BlazorTable
@using Moonlight.App.ApiClients.Wings.Resources
@using Moonlight.App.Helpers

@inject NodeRepository NodeRepository
@inject AlertService AlertService
@inject NodeService NodeService
@inject SmartTranslateService SmartTranslateService

@attribute [PermissionRequired(nameof(Permissions.AdminNodes))]

<AdminServersNavigation Index="3" />

<LazyLoader @ref="LazyLoader" Load="Load">
    <div class="card">
        <div class="card-header border-0 pt-5">
            <h3 class="card-title align-items-start flex-column">
                <span class="card-label fw-bold fs-3 mb-1">
                    <TL>Nodes</TL>
                </span>
            </h3>
            <div class="card-toolbar">
                <a href="/admin/nodes/new" class="btn btn-sm btn-light-success">
                    <i class="bx bx-layer-plus"></i>
                    <TL>New node</TL>
                </a>
            </div>
        </div>
        <div class="card-body pt-0">
            @if (Nodes.Any())
            {
                <div class="table-responsive">
                    <Table TableItem="Node" Items="Nodes" PageSize="25" TableClass="table table-row-bordered table-row-gray-100 align-middle gs-0 gy-3" TableHeadClass="fw-bold text-muted">
                        <Column TableItem="Node" Title="@(SmartTranslateService.Translate("Id"))" Field="@(x => x.Id)" Sortable="true" Filterable="true"/>
                        <Column TableItem="Node" Title="@(SmartTranslateService.Translate("Status"))" Field="@(x => x.Id)" Sortable="true" Filterable="true">
                            <Template>
                                @{
                                    var ss = StatusCache.ContainsKey(context) ? StatusCache[context] : null;
                                }

                                @if (ss == null)
                                {
                                    <span class="text-danger">Offline</span>
                                }
                                else
                                {
                                    <span class="text-success">Online (@(ss.Version))</span>
                                }
                            </Template>
                        </Column>
                        <Column TableItem="Node" Title="@(SmartTranslateService.Translate("Name"))" Field="@(x => x.Name)" Sortable="true" Filterable="true">
                            <Template>
                                <a href="/admin/nodes/view/@(context.Id)">@(context.Name)</a>
                            </Template>
                        </Column>
                        <Column TableItem="Node" Title="@(SmartTranslateService.Translate("Fqdn"))" Field="@(x => x.Fqdn)" Sortable="true" Filterable="true"/>
                        <Column TableItem="Node" Title="" Field="@(x => x.Id)" Sortable="false" Filterable="false">
                            <Template>
                                <a href="/admin/nodes/edit/@(context.Id)">
                                    @(SmartTranslateService.Translate("Edit"))
                                </a>
                            </Template>
                        </Column>
                        <Column TableItem="Node" Title="" Field="@(x => x.Id)" Sortable="false" Filterable="false">
                            <Template>
                                <a href="/admin/nodes/setup/@(context.Id)">
                                    @(SmartTranslateService.Translate("Setup"))
                                </a>
                            </Template>
                        </Column>
                        <Column TableItem="Node" Title="" Field="@(x => x.Id)" Sortable="false" Filterable="false">
                            <Template>
                                <WButton Text="@(SmartTranslateService.Translate("Delete"))"
                                         WorkingText="@(SmartTranslateService.Translate("Deleting"))"
                                         CssClasses="btn-sm btn-danger"
                                         OnClick="() => Delete(context)">
                                </WButton>
                            </Template>
                        </Column>
                        <Pager ShowPageNumber="true" ShowTotalCount="true"/>
                    </Table>
                </div>
            }
            else
            {
                <div class="alert alert-info">
                    <TL>No nodes found</TL>
                </div>
            }
        </div>
    </div>
</LazyLoader>

@code
{
    private Node[] Nodes;

    private LazyLoader LazyLoader;

    private Dictionary<Node, SystemStatus?> StatusCache = new();

    private Task Load(LazyLoader lazyLoader)
    {
        lock (StatusCache)
        {
            StatusCache.Clear();
        }

        Nodes = NodeRepository.Get().ToArray();

        Task.Run(() =>
        {
            foreach (var node in Nodes)
            {
                Task.Run(async () =>
                {
                    try
                    {
                        var ss = await NodeService.GetStatus(node);

                        lock (StatusCache)
                        {
                            StatusCache.Add(node, ss);
                        }
                    }
                    catch (Exception e)
                    {
                        Logger.Verbose($"Error fetching status for node '{node.Name}'");
                        Logger.Verbose(e);
                    }

                    await InvokeAsync(StateHasChanged);
                });
            }
        });

        return Task.CompletedTask;
    }

    private async Task Delete(Node node)
    {
        var b = await AlertService.YesNo(
            SmartTranslateService.Translate("Delete this node?"),
            SmartTranslateService.Translate("Do you really want to delete this node"),
            SmartTranslateService.Translate("Yes"),
            SmartTranslateService.Translate("No")
            );

        if (b)
        {
            if (node.Allocations.Any())
                await AlertService.Error(
                    SmartTranslateService.Translate("Error"),
                    SmartTranslateService.Translate("Delete all allocations before deleting the node")
                    );
            else
            {
                NodeRepository.Delete(node);
                await LazyLoader.Reload();
            }
        }
    }
}