using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

using C1.Silverlight.Chart;

namespace ChartSamples
{
  [System.ComponentModel.Description("Click on pie slice to see animation")]
  public partial class PieAnimation : UserControl
  {
    public PieAnimation()
    {
      InitializeComponent();

      var ds = new DataSeries() { ValuesSource = new double[] { 1, 2, 3, 4 } };
      ds.PlotElementLoaded += new EventHandler(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.MouseLeftButtonDown += new MouseButtonEventHandler(slice_MouseLeftButtonDown);

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

    void slice_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
      var slice = (PieSlice)sender;

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

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

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

      da.To = to;

      sb.Children.Add(da);

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

      sb.Begin();
    }
  }
}
