@using Radzen.Blazor

<span class="rz-legend-item" style="@Style" @onclick="@OnClick" tabindex="0" @onkeypress="@OnKeyPress" @onkeypress:preventDefault=@preventKeyPress @onkeypress:stopPropagation>
    <svg width="@((MarkerSize * 2).ToInvariantString())" height="@((MarkerSize * 2).ToInvariantString())">
        <g class="rz-series-@Index @Class">
            <Marker X="@MarkerSize" Y="@MarkerSize" Type="@(MarkerType == MarkerType.None ? MarkerType.Square : MarkerType)" Fill="@Color" Size="@MarkerSize" />
        </g>
    </svg>
    <span class="rz-legend-item-text">@Text</span>
</span>

@code {
    [Parameter]
    public string Color { get; set; } = string.Empty;

    [Parameter]
    public string Text { get; set; } = string.Empty;

    [Parameter]
    public string Class { get; set;} = string.Empty;

    [Parameter]
    public string Style { get; set; } = string.Empty;

    [Parameter]
    public MarkerType MarkerType { get; set; }

    [Parameter]
    public double MarkerSize { get; set; }

    [Parameter]
    public EventCallback Click { get; set; }

    [Parameter]
    public bool Clickable { get; set; } = true;

    [Parameter]
    public int Index { get; set; }

    bool preventKeyPress;

    async Task OnClick()
    {
        if (Clickable)
        {
            await Click.InvokeAsync();
        }
    }

    async Task OnKeyPress(KeyboardEventArgs args)
    {
        var key = args.Code != null ? args.Code : args.Key;

        if (key == "Space" || key == "Enter")
        {
            preventKeyPress = true;

            await OnClick();
        }
        else
        {
            preventKeyPress = false;
        }
    }
}
