@using Radzen.Blazor.Rendering
@typeparam TItem
@inherits Radzen.Blazor.CartesianSeries<TItem>

<CascadingValue Value="@this">
  @ChildContent
</CascadingValue>

@code {
    public override CoordinateSystem CoordinateSystem => CoordinateSystem.Polar;

    public override RenderFragment Render(ScaleBase categoryScale, ScaleBase valueScale)
    {
        var chart = RequireChart();
        var className = $"rz-pie-series rz-series-{chart.Series.IndexOf(this)}";
        var x = CenterX;
        var y = CenterY;
        var radius = CurrentRadius;
        var items = PositiveItems;

        return
        @<g class="@className">
            @if (items.Any())
                {
                    var sum = items.Sum(Value);
                    var startAngle = StartAngle;

                @foreach (var data in items)
                    {
                        var value = Value(data);
                        var sweepAngle = sum == 0 ? 0 : (value / sum) * TotalAngle;
                        var endAngle = startAngle - sweepAngle;

                        var d = Segment(x, y, radius, 0, startAngle, endAngle);

                        startAngle = endAngle;

                        var index = Items.IndexOf(data);
                        var arcClassName = $"rz-series-item-{index}";
                        var fill = PickColor(index, Fills);
                        var stroke = PickColor(index, Strokes);

                        <g class="@arcClassName">
                            @if (sweepAngle > 0)
                            {
                                <Path D="@d" Fill="@fill" StrokeWidth="@StrokeWidth" Stroke="@stroke" />
                            }
                        </g>
                    }
                }
                else
                {
                    var arcClassName = $"rz-series-item-0";
                    var d = Segment(x, y, radius, radius - 1, StartAngle, StartAngle - TotalAngle);
                    var fill = PickColor(0, Fills);
                    var stroke = PickColor(0, Strokes);
                    <g class="@arcClassName">
                        <Path D="@d" Fill="@fill" StrokeWidth="@StrokeWidth" Stroke="@stroke" />
                    </g>
                }
        </g>;
    }
}
