using System.IO;
using System.Windows;
using System.Windows.Controls;
using Telerik.Windows.Persistence;
using Telerik.Windows.Persistence.Storage;

namespace SilverlightApplication1
{
	public partial class MainPage : UserControl
	{
		private Stream stream;
		private PersistenceManager manager = new PersistenceManager();
		private IsolatedStorageProvider isoProvider = new IsolatedStorageProvider();
		private bool useIsolatedStorage;

		public MainPage()
		{
			InitializeComponent();

			// The events below notify when saving and loading have been completed
			this.manager.PropertyPersistenceCompleted += this.PersistenceManager_PropertyPersistenceCompleted;
			this.manager.PropertyRestoringCompleted += this.PersistenceManager_PropertyRestoringCompleted;
		}

		private void PersistenceManager_PropertyRestoringCompleted(object sender, System.EventArgs e)
		{
			MessageBox.Show("Load Completed!");
		}

		private void PersistenceManager_PropertyPersistenceCompleted(object sender, System.EventArgs e)
		{
			MessageBox.Show("Save Completed!");
		}

		private void SaveButton_Click(object sender, RoutedEventArgs e)
		{
			// Save the current state
			this.Save();
		}

		private void LoadButton_Click(object sender, RoutedEventArgs e)
		{
			// Load the previously saved state
			this.Load();
		}

		/// <summary>
		/// Saves the current state of the TreeView control
		/// </summary>
		private void Save()
		{
			if (this.useIsolatedStorage)
			{
				this.isoProvider.SaveToStorage();
			}
			else
			{
				this.stream = this.manager.Save(this.treeView);
			}
		}

		/// <summary>
		/// Loads the last saved state of the TreeView control
		/// </summary>
		private void Load()
		{
			if (this.useIsolatedStorage)
			{
				this.isoProvider.LoadFromStorage();
			}
			else
			{
				this.stream.Position = 0L;
				this.manager.Load(this.treeView, this.stream);
			}
		}

		private void IsolatedStorageCheckBox_Unchecked(object sender, RoutedEventArgs e)
		{
			this.useIsolatedStorage = false;
		}

		private void IsolatedStorageCheckBox_Checked(object sender, RoutedEventArgs e)
		{
			this.useIsolatedStorage = true;
		}
	}
}
