using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using System.Web.DynamicData;
using Telerik.Web.UI;
using System.Web.DynamicData.ModelProviders;
using System.Text;
using Telerik.Web.UI.DynamicData;

public partial class ListDetails : System.Web.UI.Page {
    protected void Page_Init(object sender, EventArgs e) {
        DynamicDataManager1.RegisterControl(GridView1, true /*setSelectionFromUrl*/);
        DynamicDataManager1.RegisterControl(DetailsView1);
        
    }

    protected void Page_Load(object sender, EventArgs e)
    {

        MetaTable table = GridDataSource.GetTable();
        Title = table.DisplayName;
        GridDataSource.Include = table.ForeignKeyColumnsNames;
        DetailsDataSource.Include = table.ForeignKeyColumnsNames;        

        // Disable various options if the table is readonly
        if (table.IsReadOnly)
        {
            DetailsPanel.Visible = false;
        }

        GridView1.ItemCommand += new GridCommandEventHandler(GridView1_ItemCommand);
    }
    
    void GridView1_ItemCommand(object source, GridCommandEventArgs e)
    {
        if (e.CommandName == RadGrid.ExpandCollapseCommandName)
        {            
            RadGrid detailedGrid = (RadGrid)(((Telerik.Web.UI.GridDataItem)(e.Item))).ChildItem.FindControl("DetailGridView");
            detailedGrid.Rebind();
        }        
    }

    protected void GridDetailDataSource_ItemCommand(object source, GridCommandEventArgs e)
    { 

    }
    
    protected void GridDetailDataSource_Selecting(object sender, EntityDataSourceSelectingEventArgs e)
    {   
    
        GridDataItem parentItem = ((GridNestedViewItem)e.DataSource.NamingContainer).ParentItem;
        int hierarchyIndex = parentItem != null? parentItem.ItemIndex : -1;

        if (hierarchyIndex == -1)
        {
            e.Cancel = true;
            return;
        }
        
        MetaTable masterMetaTable = GridDataSource.GetTable();
        MetaTable detailMetaTable = e.DataSource.GetTable();

        StringBuilder sb = new StringBuilder();
        if (masterMetaTable.ForeignKeyColumnsNames != string.Empty)
        {   
            //Many to One relation
            foreach (MetaColumn column in detailMetaTable.PrimaryKeyColumns)
            {
                foreach (string name in masterMetaTable.ForeignKeyColumnsNames.Split(','))
                {
                    if (sb.Length > 0)
                        sb.Append(" AND ");
                    string columnName = ((MetaForeignKeyColumn)masterMetaTable.GetColumn(name)).ForeignKeyNames.Where(n => n == name + "." + column.Name).FirstOrDefault();
                    GridTableView ownerTableView = ((GridNestedViewItem)e.DataSource.NamingContainer).OwnerTableView;
                    if (!ownerTableView.DataKeyNames.Contains(columnName))
                        continue;                    
                    sb.AppendFormat("it.{0} = '{1}'", column.Name, ownerTableView.DataKeyValues[hierarchyIndex][columnName]);
                    //break;
                }
            }
        }
        else
        { 
            //One to Many relation
            foreach (MetaColumn col in detailMetaTable.Columns)
            {
                if (col is MetaForeignKeyColumn)
                {
                    MetaForeignKeyColumn column = (MetaForeignKeyColumn)col;
                    if (column.ParentTable.Name == masterMetaTable.Name)
                    {
                        foreach (string name in column.ForeignKeyNames)
                        {
                            if (sb.Length > 0)
                                sb.Append(" AND ");
                            GridTableView ownerTableView = ((GridNestedViewItem)e.DataSource.NamingContainer).OwnerTableView;
                            string columnName = name.Split('.')[1];
                            if (!ownerTableView.DataKeyNames.Contains(columnName))
                                continue;
                            sb.AppendFormat("it.{0} = '{1}'", name, ownerTableView.DataKeyValues[hierarchyIndex][columnName]);
                            //break;                            
                        }

                        break;
                    }
                }
            }
        }

        e.DataSource.Where = sb.ToString();
    }    
    protected void DetailGridView_Init(object sender, EventArgs e)
    {                
        string detailTableName = DynamicDataRouteHandler.GetRequestContext(this.Context).RouteData.Values["details"].ToString();
        MetaModel model = ((DynamicDataRouteHandler)(DynamicDataRouteHandler.GetRequestContext(this.Context).RouteData.RouteHandler)).Model;
        MetaTable detailTable = model.GetTable(detailTableName);
        EntityDataSource GridDetailDataSource = (EntityDataSource)((sender as RadGrid).NamingContainer).FindControl("GridDetailDataSource");
        GridDetailDataSource.ContextTypeName = detailTable.DataContextType.ToString();
        GridDetailDataSource.EntitySetName = detailTableName;
    }           

    protected void OnGridViewDataBound(object sender, EventArgs e) {
        
    }
    protected void OnFilterSelectedIndexChanged(object sender, EventArgs e) {     
        DetailsView1.ChangeMode(DetailsViewMode.ReadOnly);
    }
    protected void OnGridViewRowEditing(object sender, EventArgs e) {
        DetailsView1.ChangeMode(DetailsViewMode.ReadOnly);
    }
    protected void OnGridViewSelectedIndexChanging(object sender, EventArgs e) {        
        DetailsView1.ChangeMode(DetailsViewMode.ReadOnly);
    }

    protected void OnGridViewRowCreated(object sender, GridViewRowEventArgs e) {
        SetDeleteConfirmation(e.Row);
    }

    protected void OnGridViewRowDeleted(object sender, GridViewDeletedEventArgs e) {
        DetailsView1.DataBind();
    }

    protected void OnGridViewRowUpdated(object sender, GridViewUpdatedEventArgs e) {
        DetailsView1.DataBind();
    }

    protected void OnDetailsViewItemDeleted(object sender, DetailsViewDeletedEventArgs e) {
        GridView1.DataBind();
    }

    protected void OnDetailsViewItemUpdated(object sender, DetailsViewUpdatedEventArgs e) {
        GridView1.DataBind();
    }

    protected void OnDetailsViewItemInserted(object sender, DetailsViewInsertedEventArgs e) {
        GridView1.DataBind();
    }

    protected void OnDetailsViewModeChanging(object sender, DetailsViewModeEventArgs e) {
      
    }

    protected void OnDetailsViewPreRender(object sender, EventArgs e) {
        int rowCount = DetailsView1.Rows.Count;
        if (rowCount > 0) {
            SetDeleteConfirmation(DetailsView1.Rows[rowCount - 1]);
        }
    }

    private void SetDeleteConfirmation(TableRow row) {
        foreach (Control c in row.Cells[0].Controls) {
            if (c is LinkButton) {
                LinkButton btn = (LinkButton)c;
                if (btn.CommandName == DataControlCommands.DeleteCommandName) {
                    btn.OnClientClick = "return confirm('Are you sure you want to delete this item?');";
                }
            }
        }
    }
}
