using Model.ReadWrite;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;

public partial class _Default : System.Web.UI.Page
{
    private NorthwindReadWriteEntities _dataContext;

    protected NorthwindReadWriteEntities DbContext
    {
        get
        {
            if (_dataContext == null)
            {
                _dataContext = new NorthwindReadWriteEntities();
            }
            return _dataContext;
        }
    }

    public override void Dispose()
    {
        if (_dataContext != null)
        {
            _dataContext.Dispose();
        }
        base.Dispose();
    }

    protected void RadGrid1_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
    {
        var result = from r in DbContext.Products
                     select r;

        RadGrid1.DataSource = result;
    }

    protected void RadGrid1_UpdateCommand(object source, GridCommandEventArgs e)
    {
        var editableItem = ((GridEditableItem)e.Item);
        var productId = (int)editableItem.GetDataKeyValue("ProductID");

        //retrive entity form the Db
        var product = DbContext.Products.Where(n => n.ProductID == productId).FirstOrDefault();
        if (product != null)
        {
            //update entity's state
            editableItem.UpdateValues(product);

            try
            {
                //save chanages to Db
                DbContext.SaveChanges();
            }
            catch (System.Exception)
            {
                ShowErrorMessage();
            }
        }
    }

    /// <summary>
    /// Shows a <see cref="RadWindow"/> alert if an error occurs
    /// </summary>
    private void ShowErrorMessage()
    {
        RadAjaxManager1.ResponseScripts.Add(string.Format("window.radalert(\"Please enter valid data!\")"));
    }

    protected void RadGrid1_ItemCreated(object sender, GridItemEventArgs e)
    {
        if (e.Item is GridEditableItem && (e.Item.IsInEditMode))
        {
            GridEditableItem editableItem = (GridEditableItem)e.Item;
            SetupInputManager(editableItem);
        }
    }

    private void SetupInputManager(GridEditableItem editableItem)
    {
        // style and set ProductName column's textbox as required
        var textBox =
            ((GridTextBoxColumnEditor)editableItem.EditManager.GetColumnEditor("ProductName")).TextBoxControl;


        InputSetting inputSetting = RadInputManager1.GetSettingByBehaviorID("TextBoxSetting1");
        inputSetting.TargetControls.Add(new TargetInput(textBox.UniqueID, true));
        inputSetting.InitializeOnClient = true;
        inputSetting.Validation.IsRequired = true;

        // style UnitPrice column's textbox 
        textBox =
            ((GridTextBoxColumnEditor)editableItem.EditManager.GetColumnEditor("UnitPrice")).TextBoxControl;

        inputSetting = RadInputManager1.GetSettingByBehaviorID("NumericTextBoxSetting1");
        inputSetting.InitializeOnClient = true;
        inputSetting.TargetControls.Add(new TargetInput(textBox.UniqueID, true));

        // style UnitsInStock column's textbox 
        textBox =
            ((GridTextBoxColumnEditor)editableItem.EditManager.GetColumnEditor("UnitsInStock")).TextBoxControl;


        inputSetting = RadInputManager1.GetSettingByBehaviorID("NumericTextBoxSetting2");
        inputSetting.InitializeOnClient = true;
        inputSetting.TargetControls.Add(new TargetInput(textBox.UniqueID, true));
    }

    protected void RadGrid1_InsertCommand(object source, GridCommandEventArgs e)
    {
        var editableItem = ((GridEditableItem)e.Item);
        //create new entity
        var product = new Model.ReadWrite.Product();
        //populate its properties
        Hashtable values = new Hashtable();
        editableItem.ExtractValues(values);
        product.ProductName = (string)values["ProductName"];
        if (values["UnitsInStock"] != null)
        {
            product.UnitsInStock = short.Parse(values["UnitsInStock"].ToString());
        }
        if (values["UnitPrice"] != null)
        {
            product.UnitPrice = decimal.Parse(values["UnitPrice"].ToString());
        }

        DbContext.AddToProducts(product);
        try
        {
            //save chanages to Db
            DbContext.SaveChanges();
        }
        catch (System.Exception)
        {
            ShowErrorMessage();
        }
    }

    protected void RadGrid1_DeleteCommand(object source, GridCommandEventArgs e)
    {
        var productId = (int)((GridDataItem)e.Item).GetDataKeyValue("ProductID");

        //retrive entity form the Db
        var product = DbContext.Products.Where(n => n.ProductID == productId).FirstOrDefault();
        if (product != null)
        {
            //add the product for deletion
            DbContext.Products.DeleteObject(product);
            try
            {
                //save chanages to Db
                DbContext.SaveChanges();
            }
            catch (System.Exception)
            {
                ShowErrorMessage();
            }
        }
    }
}