using System.Windows.Controls;
using System.Windows.Media.Animation;
using NorthwindBackend.NorthwindServiceReference;
using Telerik.Windows.Controls;

namespace NorthwindBackend
{
	public partial class Default : UserControl
	{
		private NorthwindDataSource DataSource { get; set; }

		private Storyboard EditViewTransition { get; set; }
		private Storyboard ViewEditTransition { get; set; }
		private Storyboard ProductSelectedTransition { get; set; }
		private ProductState ProductState { get; set; }

		public Default()
		{
			InitializeComponent();

			this.ProductState = new ProductState();

			this.EditViewTransition = this.Resources["EditViewTransition"] as Storyboard;
			this.ViewEditTransition = this.Resources["ViewEditTransition"] as Storyboard;
			this.ProductSelectedTransition = this.Resources["ProductSelectedTransition"] as Storyboard;

			this.DataContext = this.DataSource = new NorthwindDataSource();
		}

		private void RadTreeView_LoadOnDemand(object sender, Telerik.Windows.RadRoutedEventArgs e)
		{
			RadTreeViewItem treeItem = e.OriginalSource as RadTreeViewItem;

			Category category = treeItem.Item as Category;
			if (category != null)
			{
				//If the expanded item is a category, begin loading its products
				this.DataSource.BeginLoadingProducts(category);
			}
			else
			{
				//If the expanded item is a product, disable its load on demand
				// because we don't have children for the product nodes.
				treeItem.IsLoadOnDemandEnabled = false;
			}
		}

		private void RadTreeView_SelectionChanged(object sender, Telerik.Windows.Controls.SelectionChangedEventArgs e)
		{
			this.ProductSelectedTransition.Begin();

			Product product = (sender as RadTreeView).SelectedItem as Product;
			if (product != null)
			{
				//Undo the possible changes of the previously selected product
				this.ProductState.Restore();
			}
			this.DataSource.SelectedProduct = product;
		}

		private void ButtonEdit_Click(object sender, System.Windows.RoutedEventArgs e)
		{
			this.ViewEditTransition.Begin();

			//Save the product properties before editing
			this.ProductState.Save(this.DataSource.SelectedProduct);
		}

		private void ButtonSave_Click(object sender, System.Windows.RoutedEventArgs e)
		{
			this.EditViewTransition.Begin();

			this.DataSource.UpdateSelectedProduct();

			//We don't need the saved product properties anymore
			this.ProductState.Clear();
		}

		private void ButtonCancel_Click(object sender, System.Windows.RoutedEventArgs e)
		{
			this.EditViewTransition.Begin();

			//Restore the saved product properties
			this.ProductState.Restore();
		}

		private void ButtonDelete_Click(object sender, System.Windows.RoutedEventArgs e)
		{
			RadWindow.Confirm("Are you sure you want to delete this product?",
				(object window, WindowClosedEventArgs args) =>
				{
					if (args.DialogResult.HasValue && args.DialogResult.Value)
					{
						this.DataSource.DeleteSelectedProduct();
					}
				});
		}
	}
}