using C1.Xaml.Chart;
using System;
using Windows.UI.Xaml.Controls;
using CE.Controls.Chart.Appearance;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Media.Animation;


namespace ControlExplorer.Controls.Chart
{
    public partial class PieAnimation : UserControl
    {
        public PieAnimation()
        {
            InitializeComponent();

            var ds = new DataSeries() { ValuesSource = new double[] { 1, 2, 3, 4 } };
            ds.PlotElementLoaded += ds_PlotElementLoaded;

            chart.Data.Children.Add(ds);
            chart.ChartType = ChartType.Pie;

            chart.VisualEffect = new VisualEffectGroup() { Children = { new BorderEffect(), new ShadowEffect() { Softness = 0.5 } } };
        }

        void ds_PlotElementLoaded(object sender, EventArgs e)
        {
            var slice = (PieSlice)sender;
            slice.Tapped += slice_Tapped;

            var a = PieOptions.GetStartingAngle(chart);
            if (slice.Angle == -90)
                RunAnimation(slice, "Offset", TimeSpan.FromSeconds(0.5), 20, new BounceEase());
        }

        void slice_Tapped(object sender, Windows.UI.Xaml.Input.TappedRoutedEventArgs e)
        {
            var slice = (PieSlice)sender;

            RunAnimation(chart, PieOptions.StartingAngleProperty, TimeSpan.FromSeconds(0.5),
              PieOptions.GetStartingAngle(chart) - slice.Angle - 90);
        }

        void RunAnimation(DependencyObject target, string targetProperty, TimeSpan time, double to,
          EasingFunctionBase easing = null,
          System.Action action = null)
        {
            var sb = new Storyboard();
            var da = new DoubleAnimation() { Duration = time, EasingFunction = easing };

            Storyboard.SetTargetProperty(da, targetProperty);
            Storyboard.SetTarget(da, target);

            da.To = to;

            sb.Children.Add(da);

            if (action != null)
                sb.Completed += (s, e) => action();

            sb.Begin();
        }
    }
}
