using C1.WPF.Chart;
using System.Linq;
using System.Windows.Controls;
using System.Windows.Media;
using C1.Chart;

namespace FloatingBarChart
{
    /// <summary>
    /// Interaction logic for LegendItems.xaml
    /// </summary>
    public partial class FloatBar : UserControl
    {
        Series seriesA, seriesB;
        float columnWidthPercentage = 0.6f;
        public FloatBar()
        {
            InitializeComponent();
            seriesA = new Series();
            seriesA.Binding = "ClassAHigh";
            seriesA.SeriesName = "Class A";
            seriesA.SymbolRendering += SeriesA_SymbolRendering;

            seriesB = new Series();
            seriesB.Binding = "ClassBHigh";
            seriesB.SeriesName = "Class B";
            seriesB.SymbolRendering += SeriesB_SymbolRendering;
            
            flexChart.Series.Add(seriesA);
            flexChart.Series.Add(seriesB);
            flexChart.LabelRendering += FlexChart_LabelRendering;
            flexChart.AxisY.MajorUnit = 10;
            flexChart.ToolTip.Visibility = System.Windows.Visibility.Hidden;
            flexChart.DataLabel.Position = LabelPosition.Bottom;
            flexChart.DataLabel.Content = "{seriesName}";
            flexChart.Options.ClusterSize = new ElementSize() { SizeType = ElementSizeType.Percentage, Value = columnWidthPercentage * 100 };
        }

        private void FlexChart_LabelRendering(object sender, RenderDataLabelEventArgs e)
        {
            SubjectScoreRange range = (SubjectScoreRange)e.Item;
            e.Text = e.Text.Equals("Class A") ? range.ClassALow + " - " + range.ClassAHigh : range.ClassBLow + " - " + range.ClassBHigh;
        }

        private void SeriesB_SymbolRendering(object sender, RenderSymbolEventArgs e)
        {
            e.Cancel = true;
            SubjectScoreRange range = (SubjectScoreRange)e.Item;
            double width = flexChart.PlotRect.Width / seriesB.GetValues(0).Count() * columnWidthPercentage / flexChart.Series.Count;
            double bottom = flexChart.AxisY.Convert(range.ClassBLow);
            e.Engine.DrawRect(e.Point.X - width / 2, e.Point.Y, width, bottom - e.Point.Y);
        }

        private void SeriesA_SymbolRendering(object sender, RenderSymbolEventArgs e)
        {
            e.Cancel = true;
            SubjectScoreRange range = (SubjectScoreRange)e.Item;
            double width = flexChart.PlotRect.Width / seriesA.GetValues(0).Count() * columnWidthPercentage / flexChart.Series.Count;
            double bottom = flexChart.AxisY.Convert(range.ClassALow);
            e.Engine.DrawRect(e.Point.X - width / 2, e.Point.Y, width, bottom - e.Point.Y);
        }
    }
}
