@page "/Games/{id:guid}/Keys/Edit"
@inject GameService GameService
@inject KeyService KeyService
@inject NavigationManager NavigationManager

<MudGrid>
    <MudItem xs="12">
        <MudPaper Class="pa-4">
            <StandaloneCodeEditor @ref="Editor" Id="editor" ConstructionOptions="EditorConstructionOptions" />
        </MudPaper>
    </MudItem>
</MudGrid>

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

<MudFab Color="Color.Primary" OnClick="Save" StartIcon="@Icons.Material.Filled.Save" Style="position: fixed; right: 32px; bottom: 32px;" />

@code {
    [Parameter] public Guid Id { get; set; }

    private Game Game { get; set; }

    private StandaloneCodeEditor Editor;

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

    protected override async Task OnInitializedAsync()
    {
        Game = await GameService.Get(Id);
    }

    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 = Game.Keys.Where(k => !keys.Contains(k.Value));
        var keysAdded = keys.Where(k => !Game.Keys.Any(gk => gk.Value == k));

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

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

        NavigationManager.NavigateTo($"/Games/{Game.Id}/Keys");
    }
}
