@using Radzen.Blazor.Rendering

<Path D=@Path Stroke=@Stroke Fill=@Fill StrokeWidth=@StrokeWidth />

@code {
    [Parameter]
    public double StartAngle { get; set; }

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

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

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

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

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

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

    [Parameter]
    public double Radius { get; set; } = 0;

    private string Path { get; set; } = string.Empty;

    [Parameter]
    public Point Center { get; set; } = new Point();

    [Parameter]
    public string Stroke { get; set; } = "none";

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

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

    double Clip(double v) => Math.Max(Min, Math.Min(v, Max));

    protected override void OnParametersSet()
    {
        var startRatio = (Clip(From) - Min) / (Max - Min);
        var startAngle = StartAngle + startRatio * (EndAngle - StartAngle);

        var outerStart = Center.ToCartesian(Radius, Polar.ToRadian(startAngle - 90));
        var innerStart = Center.ToCartesian(Radius - Size, Polar.ToRadian(startAngle - 90));

        var endRatio = (Clip(To) - Min) / (Max - Min);
        var endAngle = StartAngle + endRatio * (EndAngle - StartAngle);

        var outerEnd = Center.ToCartesian(Radius, Polar.ToRadian(endAngle - 90));
        var innerEnd = Center.ToCartesian(Radius - Size, Polar.ToRadian(endAngle - 90));

        var sweep = endAngle - startAngle <= 180 ? 0 : 1;

        var innerRadius = (Radius - Size).ToInvariantString();
        var radius = Radius.ToInvariantString();

        if (Math.Abs(outerEnd.X - outerStart.X) < 0.01 && Math.Abs(outerEnd.Y - outerEnd.Y) < 0.01)
        {
            // Full circle - SVG can't render a full circle arc 
            outerEnd.X = outerEnd.X - 0.01;
        }

        if (Math.Abs(innerEnd.X - innerStart.X) < 0.01 && Math.Abs(innerEnd.Y - innerEnd.Y) < 0.01)
        {
            // Full circle - SVG can't render a full circle arc 
            innerEnd.X = innerEnd.X - 0.01;
        }

        Path = $"M {outerStart.Render()} A {radius} {radius} 0 {sweep} 1 {outerEnd.Render()} L {innerEnd.Render()} A {innerRadius} {innerRadius} 0 {sweep} 0 {innerStart.Render()} Z";
    }
}
