using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Telerik.OpenAccess;
using Telerik.WinControls;
using Telerik.WinControls.UI;

namespace _2_ORM_MyWindFormCrud
{
    public partial class RadForm1 : Telerik.WinControls.UI.RadForm
    {
        private IObjectScope _scope = NorthwindProvider.ObjectScope();

        public RadForm1()
        {

            InitializeComponent();

            cbCategories.SelectedIndex = -1;
            cbCategories.SelectedIndex = 0;

            _scope.TransactionProperties.AutomaticBegin = true;
            gvProducts.MasterGridViewTemplate.AutoSizeColumnsMode =
              GridViewAutoSizeColumnsMode.Fill;
        }

        private void cbCategories_SelectedIndexChanged(object sender, EventArgs e)
        {
            if ((sender as RadComboBox).SelectedValue != null)
            {

                int? selectValue = (int?)(sender as RadComboBox).SelectedValue;
                // select only products for this category and assign to the 
                // ObjectView DataSource
                opProduct.ObjectSource = from product in _scope.Extent<Product>()
                                       where product.CategoryID == selectValue
                                       select product;

                // display only these three columns
                gvProducts.Columns.Clear();
                gvProducts.Columns.Add(
                  new GridViewTextBoxColumn("CategoryID"));
                gvProducts.Columns.Add(
                  new GridViewTextBoxColumn("ProductName"));
                gvProducts.Columns.Add(
                  new GridViewTextBoxColumn("QuantityPerUnit"));
            }

        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close(); 
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            _scope.Transaction.Rollback();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
              opProduct.SaveAll();
            _scope.Transaction.Commit();
        }

        private void RadForm1_FormClosing(object sender, FormClosingEventArgs e)
        {
            RadMessageBox.SetThemeName(this.ThemeName);

            if (_scope.Transaction.IsDirty)
            {
                if (RadMessageBox.Show("Save all changes?", "Pending Changes",
                  MessageBoxButtons.OKCancel) == DialogResult.OK)
                {
                    opProduct.SaveAll();
                    _scope.Transaction.Commit();
                }
                else
                {
                    _scope.Transaction.Rollback();
                }
            }

        }

    }
}
