using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using Telerik.Web.UI;

public partial class Batch_Hierarchy : System.Web.UI.Page
{

    string customersKey = "customersKey";
    string ordersKey = "ordersKey";
    string orderDetailsKeys = "orderDetailsKeys";
    public List<Customer> SessionCustomers
    {
        get
        {
            if (Session[customersKey] == null || !IsPostBack)
            {
                Session[customersKey] = CustomersTable();
            }
            return (List<Customer>)Session[customersKey];
        }

        set
        {
            Session[customersKey] = value;
        }
    }

    public List<Order> SessionOrders
    {
        get
        {


            if (Session[ordersKey] == null || !IsPostBack)
            {
                Session[ordersKey] = OrdersTable();
            }
            return (List<Order>)Session[ordersKey];
        }
        set
        {
            Session[ordersKey] = value;
        }
    }

    public List<OrderDetail> SessionOrderDetails
    {
        get
        {


            if (Session[orderDetailsKeys] == null || !IsPostBack)
            {

                Session[orderDetailsKeys] = OrderDetailsTable();
            }
            return (List<OrderDetail>)Session[orderDetailsKeys];
        }
        set
        {
            Session[orderDetailsKeys] = value;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            SessionCustomers = CustomersTable();
            SessionOrders = OrdersTable();
            SessionOrderDetails = OrderDetailsTable();
        }
    }


    protected void RadGrid1_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
    {
        if (!e.IsFromDetailTable)
            (sender as RadGrid).DataSource = SessionCustomers;
    }

    protected void RadGrid1_DetailTableDataBind(object sender, Telerik.Web.UI.GridDetailTableDataBindEventArgs e)
    {
        var nestedViewItem = e.DetailTableView.NamingContainer as GridNestedViewItem;
        var parentRow = nestedViewItem.ParentItem as GridDataItem;

        if (e.DetailTableView.Name == "Orders")
        {
            var CustomerID = (int)parentRow.GetDataKeyValue("CustomerID");

            e.DetailTableView.DataSource = SessionOrders.Where(x => x.CustomerID == CustomerID);
        }
        else if (e.DetailTableView.Name == "OrderDetails")
        {
            var OrderID = (int)parentRow.GetDataKeyValue("OrderID");

            e.DetailTableView.DataSource = SessionOrderDetails.Where(x => x.OrderID == OrderID);
        }
    }

    private List<Customer> CustomersTable()
    {
        return Enumerable.Range(1, 2).Select(x => new Customer()
        {
            CustomerID = x,
            ContactName = "Name " + x,
            ContactTitle = "Title " + x,
            Address = "Address " + x,
            Country = "Country " + x
        }).ToList();
    }

    private List<Order> OrdersTable()
    {
        var orders = new List<Order>();

        orders.Add(new Order() { OrderID = 1, CustomerID = 1, Freight = 1.2, OrderDate = DateTime.Now.Date, ShipCountry = "Country 1", ShipName = "Name 1" });
        orders.Add(new Order() { OrderID = 2, CustomerID = 1, Freight = 2.2, OrderDate = DateTime.Now.Date, ShipCountry = "Country 2", ShipName = "Name 2" });
        orders.Add(new Order() { OrderID = 3, CustomerID = 2, Freight = 3.2, OrderDate = DateTime.Now.Date, ShipCountry = "Country 3", ShipName = "Name 3" });
        orders.Add(new Order() { OrderID = 4, CustomerID = 2, Freight = 4.2, OrderDate = DateTime.Now.Date, ShipCountry = "Country 4", ShipName = "Name 4" });

        return orders;
    }

    private List<OrderDetail> OrderDetailsTable()
    {
        var detail = new List<OrderDetail>();

        detail.Add(new OrderDetail() { ProductID = 1, OrderID = 1, UnitPrice = 1.1, Quantity = 1, Discount = 1 });
        detail.Add(new OrderDetail() { ProductID = 2, OrderID = 1, UnitPrice = 2.1, Quantity = 2, Discount = 2 });
        detail.Add(new OrderDetail() { ProductID = 3, OrderID = 2, UnitPrice = 3.1, Quantity = 3, Discount = 3 });
        detail.Add(new OrderDetail() { ProductID = 4, OrderID = 2, UnitPrice = 4.1, Quantity = 4, Discount = 4 });
        detail.Add(new OrderDetail() { ProductID = 5, OrderID = 3, UnitPrice = 5.1, Quantity = 1, Discount = 1 });
        detail.Add(new OrderDetail() { ProductID = 6, OrderID = 3, UnitPrice = 6.1, Quantity = 2, Discount = 2 });
        detail.Add(new OrderDetail() { ProductID = 7, OrderID = 4, UnitPrice = 7.1, Quantity = 3, Discount = 3 });
        detail.Add(new OrderDetail() { ProductID = 8, OrderID = 4, UnitPrice = 8.1, Quantity = 4, Discount = 4 });

        return detail;
    }

    public class Customer
    {
        public int CustomerID { get; set; }
        public string ContactName { get; set; }
        public string ContactTitle { get; set; }
        public string Address { get; set; }
        public string Country { get; set; }
    }
    public class Order
    {
        public int OrderID { get; set; }
        public int CustomerID { get; set; }
        public DateTime OrderDate { get; set; }
        public double Freight { get; set; }
        public string ShipName { get; set; }
        public string ShipCountry { get; set; }
    }
    public class OrderDetail
    {
        public int OrderID { get; set; }
        public int ProductID { get; set; }
        public double UnitPrice { get; set; }
        public int Quantity { get; set; }
        public double Discount { get; set; }
    }

    protected void RadGrid1_BatchEditCommand(object sender, GridBatchEditingEventArgs e)
    {
        foreach (GridBatchEditingCommand command in e.Commands)
        {
            Hashtable newValues = command.NewValues;
            Hashtable oldValues = command.OldValues;


            switch (command.Type)
            {
                case GridBatchEditingCommandType.Insert:
                    if (command.OwnerTableView.Name == "Customers")
                    {
                        int newId = SessionCustomers.Max(x => x.CustomerID) + 1;

                        Customer newCustomer = new Customer()
                        {
                            CustomerID = newId,
                            Address = newValues["Address"].ToString(),
                            ContactName = newValues["ContactName"].ToString(),
                            ContactTitle = newValues["ContactTitle"].ToString(),
                            Country = newValues["Country"].ToString()
                        };

                        SessionCustomers.Add(newCustomer);

                    }
                    else if (command.OwnerTableView.Name == "Orders")
                    {
                        int newId = SessionOrders.Max(x => x.OrderID) + 1;
                        int customerId = (int)(command.OwnerTableView.NamingContainer as GridNestedViewItem).ParentItem.GetDataKeyValue("CustomerID");

                        Order newOrder = new Order()
                        {
                            OrderID = newId,
                            CustomerID = customerId,
                            OrderDate = (DateTime)newValues["OrderDate"],
                            Freight = (double)newValues["Freight"],
                            ShipName = newValues["ShipName"].ToString(),
                            ShipCountry = newValues["ShipCountry"].ToString()
                        };

                        SessionOrders.Add(newOrder);

                    }
                    else if (command.OwnerTableView.Name == "OrderDetails")
                    {
                        int newId = SessionOrderDetails.Max(x => x.ProductID) + 1;
                        int orderId = (int)(command.OwnerTableView.NamingContainer as GridNestedViewItem).ParentItem.GetDataKeyValue("OrderID");

                        OrderDetail newOrderDetail = new OrderDetail()
                        {
                            ProductID = newId,
                            OrderID = orderId,
                            Quantity = (int)newValues["Quantity"],
                            Discount = (double)newValues["Discount"],
                            UnitPrice = (double)newValues["UnitPrice"]
                        };

                        SessionOrderDetails.Add(newOrderDetail);
                    }

                    break;
                case GridBatchEditingCommandType.Update:

                    if (command.OwnerTableView.Name == "Customers")
                    {
                        int customerId = (int)newValues["CustomerID"];
                        Customer updatedCustomer = SessionCustomers.Where(x => x.CustomerID == customerId).FirstOrDefault();

                        updatedCustomer.CustomerID = customerId;
                        updatedCustomer.Address = newValues["Address"].ToString();
                        updatedCustomer.ContactName = newValues["ContactName"].ToString();
                        updatedCustomer.ContactTitle = newValues["ContactTitle"].ToString();
                        updatedCustomer.Country = newValues["Country"].ToString();

                    }
                    else if (command.OwnerTableView.Name == "Orders")
                    {
                        int orderId = (int)newValues["OrderID"];
                        Order updatedOrder = SessionOrders.Where(x => x.CustomerID == orderId).FirstOrDefault();

                        updatedOrder.OrderID = orderId;
                        updatedOrder.CustomerID = (int)newValues["CustomerID"];
                        updatedOrder.OrderDate = (DateTime)newValues["OrderDate"];
                        updatedOrder.Freight = (double)newValues["Freight"];
                        updatedOrder.ShipName = (string)newValues["ShipName"];
                        updatedOrder.ShipCountry = (string)newValues["ShipCountry"];

                    }
                    else if (command.OwnerTableView.Name == "OrderDetails")
                    {
                        int productId = (int)newValues["ProductID"];

                        OrderDetail updatedOrderDetail = SessionOrderDetails.Where(x => x.ProductID == productId).FirstOrDefault();

                        updatedOrderDetail.ProductID = productId;
                        updatedOrderDetail.OrderID = (int)newValues["OrderID"];
                        updatedOrderDetail.Quantity = (int)newValues["Quantity"];
                        updatedOrderDetail.Discount = (double)newValues["Discount"];
                        updatedOrderDetail.UnitPrice = (double)newValues["UnitPrice"];
                    }
                    break;
                case GridBatchEditingCommandType.Delete:

                    if (command.OwnerTableView.Name == "Customers")
                    {
                        int customerId = (int)newValues["CustomerID"];
                        Customer deletedCustomer = SessionCustomers.Where(x => x.CustomerID == customerId).FirstOrDefault();

                        SessionCustomers.Remove(deletedCustomer);

                    }
                    else if (command.OwnerTableView.Name == "Orders")
                    {
                        int orderID = (int)newValues["OrderID"];
                        Order deletedCustomer = SessionOrders.Where(x => x.OrderID == orderID).FirstOrDefault();

                        SessionOrders.Remove(deletedCustomer);

                    }
                    else if (command.OwnerTableView.Name == "OrderDetails")
                    {
                        int productId = (int)newValues["ProductID"];
                        OrderDetail deletedCustomer = SessionOrderDetails.Where(x => x.ProductID == productId).FirstOrDefault();

                        SessionOrderDetails.Remove(deletedCustomer);

                    }

                    break;
                default:
                    break;
            }
        }
    }
}