@inject IJSRuntime JSRuntime
@implements IDisposable

<path @ref="Ref" />

@code {
    [Parameter, EditorRequired]
    public EdgeModel Model { get; set; } = null!;

    [Parameter]
    public EventCallback<EdgeModel> DoubleClick { get; set; }

    [CascadingParameter]
    protected bool MapIsActive { get; set; }

    private ElementReference Ref;

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        await base.OnAfterRenderAsync(firstRender);
        if (!firstRender) return;

        await UpdatePathData();
    }

    private async Task UpdatePathData()
    {
        var data = $"M {Model.X1} {Model.Y1}";

        if (Model.TrajectoryDegree == TrajectoryDegree.One)
        {
            data = $"{data} L {(Model.X1 + Model.X2) / 2} {(Model.Y1 + Model.Y2) / 2} L {Model.X2} {Model.Y2}";
        }
        else if (Model.TrajectoryDegree == TrajectoryDegree.Two)
        {
            data = $"{data} Q {Model.ControlPoint1X} {Model.ControlPoint1Y} {Model.X2} {Model.Y2}";
        }
        else if (Model.TrajectoryDegree == TrajectoryDegree.Three)
        {
            data = $"{data} C {Model.ControlPoint1X} {Model.ControlPoint1Y}, {Model.ControlPoint2X} {Model.ControlPoint2Y}, {Model.X2} {Model.Y2}";
        }

        await JSRuntime.InvokeVoidAsync("ElementSetAttribute", Ref, "d", data);
    }

    public void Dispose()
    {
        GC.SuppressFinalize(this);
    }
}
