using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Example_LINQ.Model;
using System.Data;
using Telerik.Windows.Data;

namespace Example_LINQ
{
	/// <summary>
	/// Interaction logic for MainWindow.xaml
	/// </summary>
	public partial class MainWindow : Window
	{
		NorthwindDataContext db = new NorthwindDataContext();
		QueryableCollectionView view;


		DataSet myDataSet = new DataSet();
		
		public MainWindow()
		{
			InitializeComponent();

			this.view = new QueryableCollectionView(db.Customers);

			this.RadGridView1.ItemsSource = this.view;
			this.RadGridView1.AddingNewDataItem += this.RadGridView1_AddingNewDataItem;
			this.RadGridView1.RowEditEnded += new EventHandler<Telerik.Windows.Controls.GridViewRowEditEndedEventArgs>(RadGridView1_RowEditEnded);			
			
		}

		void RadGridView1_RowEditEnded(object sender, Telerik.Windows.Controls.GridViewRowEditEndedEventArgs e)
		{
			if (e.EditAction == Telerik.Windows.Controls.GridView.GridViewEditAction.Commit && e.EditOperationType == Telerik.Windows.Controls.GridView.GridViewEditOperationType.Insert)
			{
				this.db.Customers.InsertOnSubmit(e.EditedItem as Customer);
				this.db.SubmitChanges();
				this.db.Refresh(System.Data.Linq.RefreshMode.KeepChanges, this.db.Customers);
				this.RadGridView1.ShowInsertRow = false;
				this.RadGridView1.Rebind();
			}
		}

		void RadGridView1_AddingNewDataItem(object sender, Telerik.Windows.Controls.GridView.GridViewAddingNewEventArgs e)
		{
			e.NewObject = new Customer();		
		}

		private void InsertButton_Click(object sender, RoutedEventArgs e)
		{
			this.RadGridView1.BeginInsert();
			db.SubmitChanges();
		}

		private void DeleteButton_Click(object sender, RoutedEventArgs e)
		{
			var selectedItem = this.RadGridView1.SelectedItem as Customer;
			if (selectedItem != null)
			{
				this.db.Customers.DeleteOnSubmit(selectedItem);
				this.db.SubmitChanges();

				this.RadGridView1.Rebind();
			}
		}

		private void UpdateButton_Click(object sender, RoutedEventArgs e)
		{
			this.db.SubmitChanges();
			this.RadGridView1.Rebind();
		}

		}
	
}
