using System;
using System.Collections.Generic;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Animation;
using Windows.UI.Xaml.Navigation;
using Windows.UI.Xaml.Shapes;

using C1.Xaml.Chart;

namespace ChartSamples
{
  public sealed partial class Animation : UserControl
  {
    Dictionary<string, PlotElement> _dict = new Dictionary<string, PlotElement>();
    
    public Animation()
    {
      this.InitializeComponent();

      chart.View.AxisY.Min = 0;
      chart.View.AxisY.Max = 100;
      BarColumnOptions.SetRadiusX(chart, 2);
      BarColumnOptions.SetRadiusY(chart, 2);
      chart.ChartType = ChartType.Column;

      NewData();
    }

    Random rnd = new Random();

    void NewData()
    {
      // create new random data values
      int cnt = 12;
      double[] vals = new double[cnt];
      for (int i = 0; i < cnt; i++)
        vals[i] = rnd.Next(10, 100);

      DataSeries ds;
      if (chart.Data.Children.Count == 0)
      {
          ds = new DataSeries() { Label = "series1" };
        ds.PlotElementLoaded += new EventHandler(ds_PlotElementLoaded);
        chart.Data.Children.Add(ds);
      }
      chart.Data.Children[0].ValuesSource = vals;
    }

    void ds_PlotElementLoaded(object sender, EventArgs e)
    {
      var pe = (PlotElement)sender;
      string key = GetKey(pe);
      if (_dict.ContainsKey(key))
      {
        var pe0 = _dict[key];
        Rect rc0 = ((Path)pe0.Shape).Data.Bounds;
        Rect rc = ((Path)pe.Shape).Data.Bounds;

        if (rc0 != rc) // different values
        {
          // transform to fit into the previous value
          ScaleTransform st = new ScaleTransform()
          {
            ScaleX = rc0.Width / rc.Width,
            ScaleY = rc0.Height / rc.Height
          };
          pe.RenderTransform = st;
          pe.RenderTransformOrigin = new Point(0, 1);

          // animate to the current value
          Storyboard sb = new Storyboard() { Duration = new Duration(TimeSpan.FromSeconds(3)) };
          DoubleAnimation da1 = new DoubleAnimation() { To = 1.0 };
          Storyboard.SetTarget(da1, st);
          Storyboard.SetTargetProperty(da1, "ScaleX");
          sb.Children.Add(da1);
          DoubleAnimation da2 = new DoubleAnimation() { To = 1.0 };
          Storyboard.SetTarget(da2, st);
          Storyboard.SetTargetProperty(da2, "ScaleY");
          sb.Children.Add(da2);
          sb.Begin();
        }
      }
      // store the previous element into the dictionary
      _dict[key] = pe;
    }

    static string GetKey(PlotElement pe)
    {
      return string.Format("s{0}p{1}", pe.DataPoint.SeriesIndex, pe.DataPoint.PointIndex);
    }

    private void btnNew_Click(object sender, RoutedEventArgs e)
    {
      NewData();
    }
  }
}
