@page "/todoliste"
@using DxBlazorApplication2.Components.Formen
@using DxBlazorApplication2.Services;
@rendermode InteractiveServer
@inject TodoService _todoService;
@inject IJSRuntime JSRuntime
@implements IDisposable

<script>
        window.registerKeyDown = (dotnetHelper) => {
        document.addEventListener('keydown', (event) => {
              if (event.key === 'F1' || event.key === 'F2' || event.key === 'F3' || event.key === 'F4' || event.key === 'F5' || event.key === 'F6' || 
              event.key === 'F7' || event.key === 'F8' || event.key === 'F9' || event.key === 'F10' || event.key === 'F11' || event.key === 'F12' ||
              event.key === 'Escape' || event.key === 'PageDown' || event.key === 'PageUp')
              {
                  if(!event.ctrlKey && !event.altKey && !event.metaKey)
                  {
                    dotnetHelper.invokeMethodAsync('KeyDownHandler', event.key, event.shiftKey);
                    event.preventDefault();
                  }
              }
              else
              {
                    //dotnetHelper.invokeMethodAsync('KeyDownHandler', event.key + "(nicht abgefangen)", event.shiftKey, event.ctrlKey);
              }
        });
    };
</script>

<PageTitle>ToDo-Liste</PageTitle>

<div class="border" style="padding: 20px">
    <h4>Neues ToDo</h4>
    <TodoItemForm/>
</div>

<div class="border" style="padding: 20px; margin-top: 20px;">
    <div style="display: flex; flex-direction: column">
        @foreach (var todo in Todos)
        {
            <div style="display: flex; margin-bottom: 10px;">
                <div style="display: flex align-items: center; margin-bottom: 10px">
                    <div class="@ItemClass(todo)" style="width: 280px;">@todo.Text</div>
                </div>
                @if (todo.Completed)
                {
                    <div style="width: 120px">
                        <button class="btn btn-primary" onclick="@(() => UncompleteItem(todo))">Offen</button>
                    </div>
                }
                @if (!todo.Completed)
                {
                    <div style="width: 120px">
                        <button class="btn btn-primary" onclick="@(() => CompleteItem(todo))">Erledigt</button>
                    </div>
                }
                <div>
                    <buttin class="btn btn-danger" onclick="@(() => RemoveItem(todo))">Löschen</buttin>
                </div>
            </div>
        }
    </div>

    <div>
        <p>Gedrückte Taste: @LastKeyPressed</p>
    </div>


</div>

@code 
{
    private List<TodoItem> Todos { get; set; } = new List<TodoItem>();

    protected override void OnInitialized()
    {
        this._todoService.OnToDoListeChanged += this.OnToDoListeChanged;
        Todos = _todoService.GetItems().ToList();
    }

    public string ItemClass(TodoItem item)
    {
        return item.Completed ? "item-completed" : "";
    }

    public void RemoveItem(TodoItem item)
    {
        _todoService.RemoveItem(item);
    }

    public void CompleteItem(TodoItem item)
    {
        _todoService.Complete(item);
    }
    public void UncompleteItem(TodoItem item)
    {
        _todoService.Uncomplete(item);
    }


    private string LastKeyPressed { get; set; } = "N/A";
    private DotNetObjectReference<ToDoListe>? objRef;

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            objRef = DotNetObjectReference.Create(this);
            await JSRuntime.InvokeVoidAsync("registerKeyDown", objRef);
        }
    }

    [JSInvokable]
    public void KeyDownHandler(string key, bool shiftKey)
    {
        if (shiftKey)
            LastKeyPressed = "[Shift]" + key;
        else
            LastKeyPressed = key;
        StateHasChanged();
    }

    public void Dispose()
    {
        // Spannend, wann das aufgerufen wird
        // Anscheinend einmal nach dem Aufruf der Seite und auch beim Verlassen der Seite
        objRef?.Dispose();
    }

    public async void OnToDoListeChanged(object sender, ToDoListeEventArgs args)
    {
        await InvokeAsync(() =>
        {
            Todos = _todoService.GetItems().ToList();
            StateHasChanged();
        });
    }

}