using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Telerik.Windows.Data;
using System.Collections.ObjectModel;
using System.Windows.Threading;
using System.Linq;

namespace SparkLinesInGridView
{
    public class MyDataContext
    {
        string letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        Random rnd;

        ObservableCollection<StockData> _Source;
        ObservableCollection<StockData> Source
        {
            get
            {
                if (_Source == null)
                {
                    rnd = new Random();

                    _Source = new ObservableCollection<StockData>(from i in Enumerable.Range(0, 18) select CreateStockData());

                    DispatcherTimer timer = new DispatcherTimer();
                    timer.Interval = TimeSpan.FromMilliseconds(50);
                    timer.Tick += new EventHandler(timer_Tick);
                    timer.Start();
                }

                return _Source;
            }
        }

        void timer_Tick(object sender, EventArgs e)
        {
            int index = rnd.Next(0, this.Source.Count());
            StockData item = CreateStockData();
            Source[index] = item;
        }

        private StockData CreateStockData()
        {
            StockData item = new StockData();
            item.Name = String.Format("{0}{1}{2}{3}", letters[rnd.Next(0, letters.Count())], letters[rnd.Next(0, letters.Count())], 
                letters[rnd.Next(0, letters.Count())], letters[rnd.Next(0, letters.Count())]);
            item.LastUpdate = DateTime.Now;
            item.Change = rnd.NextDouble();
            var trendData = new double[20];

            for (int i = 0; i < 20; i++)
                trendData[i] = rnd.NextDouble();

            item.Trend = trendData;

            return item;
        }

        QueryableCollectionView _Data;
        public QueryableCollectionView Data
        {
            get
            {
                if (_Data == null)
                {
                    _Data = new QueryableCollectionView(Source);
                    _Data.SortDescriptors.Add(new SortDescriptor()
                    {
                        Member = "Name",
                        SortDirection = System.ComponentModel.ListSortDirection.Descending
                    });
                }

                return _Data;
            }
        }
    }

    public class StockData
    {
        public string Name { get; set; }
        public double Change { get; set; }
        public DateTime LastUpdate { get; set; }
        public double[] Trend { get; set; }

    }
}
