using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using Telerik.Windows.Controls.Charting;
using System.Windows;

namespace SilverlightApplication1
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();

            List<int> data = new List<int>();
            Random rand = new Random(123456);
            for (int i = 0; i < 50; i++)
            {
                data.Add(rand.Next(10, 100));
            }

            RadChart1.DefaultSeriesDefinition = new LineSeriesDefinition() { ShowItemLabels = false, ShowPointMarks = false };
            RadChart1.DefaultView.ChartArea.AxisX.LabelStep = 25;
            RadChart1.DefaultView.ChartArea.EnableAnimations = false;
            RadChart1.ItemsSource = data;

            this.PreGenerateChartSnapshot();
        }

        private void PreGenerateChartSnapshot()
        { 
            // Pre-generate the snapshot in order to avoid the lag on first splitter resize.
            DispatcherTimer timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromMilliseconds(50);
            timer.Tick += this.TimerTick;
            timer.Start();
        }

        private void TimerTick(object sender, EventArgs e)
        {
            // Generate the snapshot only once.
            (sender as DispatcherTimer).Stop();

            this.GenerateChartSnapshot();
        }

        private void GenerateChartSnapshot()
        {
            using (MemoryStream stream = new MemoryStream())
            {
                RadChart1.ExportToImage(stream);
                BitmapImage bitmapImage = new BitmapImage();
                bitmapImage.SetSource(stream);
                ChartSnapshotImage.Source = bitmapImage;
            }
        }

        private void GridSplitterMouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            RadChart1.Visibility = System.Windows.Visibility.Collapsed;
            ChartSnapshotImage.Visibility = System.Windows.Visibility.Visible;
        }

        private void GridSplitterMouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            RadChart1.Visibility = System.Windows.Visibility.Visible;
            ChartSnapshotImage.Visibility = System.Windows.Visibility.Collapsed;
        }
    }
}
