@inject KeyService KeyService
@inject IMessageService MessageService

@if (Keys != null)
{
    <Space Direction="@DirectionVHType.Vertical" Style="width: 100%;">
        <SpaceItem>
            <GridRow>
                <GridCol Span="8">
                    <Statistic Title="Available" Value="Keys.Count - AllocatedKeys" Style="text-align: center;" />
                </GridCol>
                <GridCol Span="8">
                    <Statistic Title="Allocated" Value="AllocatedKeys" Style="text-align: center;" />
                </GridCol>
                <GridCol Span="8">
                    <Statistic Title="Total" Value="Keys.Count" Style="text-align: center;" />
                </GridCol>
            </GridRow>
        </SpaceItem>

        <SpaceItem>
            <Table TItem="Key" DataSource="@Keys" Responsive>
                <PropertyColumn Property="k => k.Value">
                    <InputPassword @bind-Value="@context.Value" />
                </PropertyColumn>
                <PropertyColumn Property="k => k.AllocationMethod" Title="Allocation Method" />
                <Column TData="string" Title="Claimed By">
                    @switch (context.AllocationMethod)
                    {
                        case KeyAllocationMethod.MacAddress:
                            <text>@context.ClaimedByMacAddress</text>
                            break;

                        case KeyAllocationMethod.UserAccount:
                            <text>@context.ClaimedByUser?.UserName</text>
                            break;
                    }
                </Column>
                <PropertyColumn Property="g => g.ClaimedOn" Format="MM/dd/yyyy hh:mm tt" Title="Claimed On" Sortable />
                <ActionColumn Title="">
                    <Space Style="display: flex; justify-content: end">
                        <SpaceItem>
                            @if (context.IsAllocated())
                            {
                                <Button OnClick="() => Release(context)">Release</Button>
                            }
                        </SpaceItem>
                    </Space>
                </ActionColumn>
            </Table>
        </SpaceItem>
    </Space>

    <Modal Title="Edit Keys" Visible="EditModalVisible" Maximizable="false" DefaultMaximized="true" OnCancel="() => EditModalVisible = false" OnOk="Save">
        <StandaloneCodeEditor @ref="Editor" Id="editor" ConstructionOptions="EditorConstructionOptions" />
    </Modal>
}

<style>
    .monaco-editor-container {
        height: 600px;
    }
</style>

@code {
    [Parameter] public Guid GameId { get; set; }
    [Parameter] public ICollection<Key> Keys { get; set; }
    [Parameter] public EventCallback<ICollection<Key>> KeysChanged { get; set; }

    int AllocatedKeys;

    bool EditModalVisible = false;

    private StandaloneCodeEditor? Editor;

    private StandaloneEditorConstructionOptions EditorConstructionOptions(StandaloneCodeEditor editor)
    {
        return new StandaloneEditorConstructionOptions
        {
            AutomaticLayout = true,
            Language = "text",
            Value = String.Join('\n', Keys.Select(k => k.Value)),
            Theme = "vs-dark",
        };
    }

    protected override async Task OnInitializedAsync()
    {
        if (Keys == null)
            Keys = new List<Key>();

        AllocatedKeys = Keys.Count(k => k.IsAllocated());
    }

    public void Edit()
    {
        EditModalVisible = true;
    }

    private async Task Release(Key key)
    {
        key = await KeyService.Release(key);

        await MessageService.Success("Key was unallocated!");
    }

    private async Task Save()
    {
        var value = await Editor.GetValue();
        var keys = value.Split("\n").Select(k => k.Trim()).Where(k => !String.IsNullOrWhiteSpace(k));

        var keysDeleted = Keys.Where(k => !keys.Contains(k.Value));
        var keysAdded = keys.Where(k => !Keys.Any(gk => gk.Value == k));

        foreach (var key in keysDeleted)
            KeyService.Delete(key);

        foreach (var key in keysAdded)
            await KeyService.Add(new Key()
                {
                    GameId = GameId,
                    Value = key
                });

        EditModalVisible = false;

        await MessageService.Success("Keys updated!");
    }
}
