using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI;
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.Navigation;

using C1.Xaml.Chart;

namespace ChartSamples
{
  public sealed partial class Dynamic : UserControl
  {
    ObservableCollection<Point> _pts = new ObservableCollection<Point>();
    int counter = 0;
    Random rnd = new Random();
    DispatcherTimer dt;
    int nMaxPoints = 60;
    int nAddPoints = 1;
    //TrendLine _tlmin, _tlmax, _tlavg;

    public Dynamic()
    {
      this.InitializeComponent();

      chart.DataContext = _pts;
      chart.ChartType = ChartType.Line;

      XYDataSeries ds = new XYDataSeries()
      {
        XValueBinding = new Binding() { Path = new PropertyPath("X") },
        ValueBinding = new Binding() { Path = new PropertyPath("Y") },
        ConnectionStrokeThickness = 2,
        Label = "raw",
      };

      chart.Data.Children.Add(ds);

      chart.View.AxisY.Min = -1000;
      chart.View.AxisY.Max = 1000;

      dt = new DispatcherTimer() { Interval = TimeSpan.FromSeconds(0.2) };
      dt.Tick += (s, e) => Update();
      dt.Start();
    }

    void Update()
    {
      chart.BeginUpdate();

      int cnt = nAddPoints;
      for (int i = 0; i < cnt; i++)
      {
        double r = rnd.NextDouble();
        double y = (10 * r * Math.Sin(0.1 * counter) * Math.Sin(0.6 * rnd.NextDouble() * counter));
        _pts.Add(new Point(counter++, y * 100));
      }

      int ndel = _pts.Count - nMaxPoints;
      if (ndel > 0)
        for (int i = 0; i < ndel; i++)
          _pts.RemoveAt(0);

      chart.EndUpdate();
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
      Button btn = (Button)sender;

      if (dt.IsEnabled)
      {
        dt.Stop();
        btn.Content = "Start";
      }
      else
      {
        dt.Start();
        btn.Content = "Stop";
      }
    }

    internal void StopTimer()
    {
      if (dt.IsEnabled)
      {
        dt.Stop();
        btnTimer.Content = "Start";
      }
    }
  }
}
