@inject IJSRuntime JSRuntime

<polygon @ref="Ref" visibility="hidden" />
<g @ref="PointRef" visibility="hidden">
    <circle cx="@X1" cy="@Y1" />
    <circle cx="@X2" cy="@Y2" />
    <circle cx="@X3" cy="@Y3" />
    <circle cx="@X4" cy="@Y4" />
    <circle cx="@X5" cy="@Y5" />
</g>

@code {
    private ElementReference Ref;
    private ElementReference PointRef;


    public double X1 { get; private set; }
    public double Y1 { get; private set; }
    public double X2 { get; private set; }
    public double Y2 { get; private set; }
    public double X3 { get; private set; }
    public double Y3 { get; private set; }
    public double X4 { get; private set; }
    public double Y4 { get; private set; }
    public double X5 { get; private set; }
    public double Y5 { get; private set; }

    public int Step { get; private set; }

    public async Task CreateAsync(double x, double y)
    {
        if (Step == 0)
        {
            await Visible();
            Step = 1;
            X1 = x;
            Y1 = y;
        }
        else if (Step == 1) Step = 2;
        else if (Step == 2) Step = 3;
        else if (Step == 3)
        {
            X4 = x;
            Y4 = y;
            Step = 4;
            await CalculatorZone();
        }
    }

    public async Task Update(double x, double y)
    {
        if (Step == 1)
        {
            X2 = x;
            Y2 = y;
        }
        else if (Step == 2)
        {
            X3 = x;
            Y3 = y;
        }
        else if (Step == 3)
        {
            X4 = x;
            Y4 = y;
        }
        await CalculatorZone();
        StateHasChanged();
    }

    private async Task CalculatorZone()
    {
        var points = $"{X1},{Y1} {X2},{Y2}";
        if (Step == 2) points += $" {X3},{Y3}";
        if (Step == 3) points += $" {X3},{Y3} {X4},{Y4}";
        await JSRuntime.InvokeVoidAsync("ElementSetAttribute", Ref, "points", points);
    }

    public async Task Visible()
    {
        await JSRuntime.InvokeVoidAsync("ElementSetAttribute", Ref, "visibility", "visible");
        await JSRuntime.InvokeVoidAsync("ElementSetAttribute", PointRef, "visibility", "visible");
    }

    public async Task Hidden()
    {
        Step = 0;
        X1 = X2 = X3 = X4 = Y1 = Y2 = Y3 = Y4 = 0;
        await JSRuntime.InvokeVoidAsync("ElementSetAttribute", Ref, "visibility", "hidden");
        await JSRuntime.InvokeVoidAsync("ElementSetAttribute", PointRef, "visibility", "hidden");
    }
}
