using System;
using System.Drawing;
using System.Windows.Forms;
using Model; 
using Telerik.OpenAccess;
using Telerik.OpenAccess.Query;
using Telerik.WinControls;
using Telerik.WinControls.UI;

namespace MyWinFormApp
{
  public partial class RadForm1 : Telerik.WinControls.RadForm
  {

    private IObjectScope _scope = NorthwindProvider.ObjectScope();

    public RadForm1()
    {
      InitializeComponent();

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

      // just for fun, set the color of the form background
      this.FormElement.ClientFillPrimitive.BackColor =
        Color.FromArgb(159, 159, 159);
      this.FormElement.ClientFillPrimitive.BackColor2 =
        Color.FromArgb(120, 120, 120);
      this.FormElement.ClientFillPrimitive.BackColor3 =
        Color.FromArgb(110, 110, 110);
      this.FormElement.ClientFillPrimitive.GradientStyle =
        GradientStyles.OfficeGlassRect;

      _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
        ovProduct.DataSource = from product in _scope.Extent<Product>()
                               where product.CategoryID == selectValue
                               select product;

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

    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)
        {
          _scope.Transaction.Commit();
        }
        else
        {
          _scope.Transaction.Rollback();
        }
      }
    }

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

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

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