using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Telerik.Web.UI;
using System.Collections;
using System.Web.DynamicData;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Collections.Specialized;

namespace Telerik.Web.UI.DynamicData
{
    [ControlValueProperty("DataKeySelectedValue")]
    public class DynamicRadGrid : RadGrid, IControlParameterTarget, IPersistedSelector
    {
        public DynamicRadGrid()
        {
            //
        }
		
		string selectedIndex = null;

		protected override void OnLoad(EventArgs e)
		{
			if (SelectedIndexes.Count > 0)
				selectedIndex = SelectedIndexes[0];

			base.OnLoad(e);
		}

		protected override void OnDataBound(EventArgs e)
		{
			base.OnDataBound(e);

			if (selectedIndex != null)
			{
				GridItem item = Items[selectedIndex];
				if (item != null)
					item.Selected = true;
			}
			else
			{
				if (Items.Count > 0)
					Items[0].Selected = true;
			}
		}

        [Browsable(false)]
        public object DataKeySelectedValue
        {
            get
            {
                if (this.DataKey != null)
                {
                    return this.DataKey.Value;
                }
               
                return SelectedValue;
            }
        }
 
        private System.Web.UI.WebControls.DataKey _dataKey;
        public System.Web.UI.WebControls.DataKey DataKey
        {
            get
            {
                return _dataKey;
            }
            set
            {
                _dataKey = value;
                if (_dataKey != null)
                {
                    ((IStateManager)_dataKey).TrackViewState();
                }
            }
        }
		
		//protected override object SaveControlState()
		//{
		//    return new object[]{
		//        base.SaveControlState(),
		//        _dataKey != null ? ((IStateManager)_dataKey).SaveViewState() : null
		//    };
		//}
		
		//protected override void LoadControlState(object savedState)
		//{
		//    object[] controlState = (object[])savedState;
		//    base.LoadControlState(controlState[0]);
		//    if (_dataKey != null)
		//    {
		//        ((IStateManager)_dataKey).LoadViewState(controlState[1]);
		//    }
		//}

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            AllowAutomaticUpdates = true;
            AllowAutomaticDeletes = true;

            MetaTable metaTable = this.FindMetaTable();

            List<string> list = new List<string>();
            foreach (MetaColumn column in metaTable.PrimaryKeyColumns)
            {
                list.Add(column.Name);
            }
            MasterTableView.DataKeyNames = list.ToArray();

            foreach (MetaColumn column in metaTable.Columns)
            {
                if (!column.Scaffold || column.IsLongString || column is MetaChildrenColumn)
                {
                    continue;
                }

                DynamicGridBoundColumn gridColumn = new DynamicGridBoundColumn();

                gridColumn.DataField = column.Name;
                gridColumn.ConvertEmptyStringToNull = column.ConvertEmptyStringToNull;
                gridColumn.DataFormatString = column.DataFormatString;
                gridColumn.UIHint = column.UIHint;
                gridColumn.HtmlEncode = column.HtmlEncode;
                gridColumn.NullDisplayText = column.NullDisplayText;
                gridColumn.ApplyFormatInEditMode = column.ApplyFormatInEditMode;
                gridColumn.HeaderText = column.DisplayName;

                MasterTableView.Columns.Add(gridColumn);
            }
        }

        public string GetPropertyNameExpression(string columnName)
        {
            return "DataKeySelectedValue";
        }

        MetaTable IControlParameterTarget.Table
        {
            get
            {
                return this.FindMetaTable();
            }
        }

        public virtual MetaColumn FilteredColumn
        {
            get
            {
                return null;
            }
        }
    }

    public class DynamicGridBoundColumn : GridBoundColumn
    {
        private bool? _applyFormatInEditMode;
        private bool? _convertEmptyStringToNull;
        private string _dataField;
        private string _dataFormatString;
        private bool _htmlEncode = true;
        private string _nullDisplayText;
        private MetaColumn _column;

        public override void FillValues(IDictionary newValues, GridEditableItem editableItem)
        {
            OrderedDictionary values = new OrderedDictionary();

            ExtractValuesFromBindableControls(values, editableItem);

            foreach (DictionaryEntry entry in values)
            {
                if (!newValues.Contains(entry.Key))
                {
                    newValues.Add(entry.Key, entry.Value);
                }
            }
        }

        internal static void ExtractValuesFromBindableControls(IOrderedDictionary dictionary, Control container)
        {
            IBindableControl control = container as IBindableControl;
            if (control != null)
            {
                control.ExtractValues(dictionary);
            }
            foreach (Control control2 in container.Controls)
            {
                ExtractValuesFromBindableControls(dictionary, control2);
            }
        }

        public override void InitializeCell(TableCell cell, int columnIndex, GridItem inItem)
        {
            if (inItem is GridEditableItem)
            {
                DynamicControl dynamicControl = new DynamicControl();
                dynamicControl.DataField = DataField;

                bool isInsert = inItem is GridEditFormInsertItem || inItem is GridDataInsertItem;

                if (isInsert)
                    dynamicControl.Mode = DataBoundControlMode.Insert;

                if (inItem.IsInEditMode)
                    dynamicControl.Mode = DataBoundControlMode.Edit;

                dynamicControl.UIHint = UIHint;
                dynamicControl.HtmlEncode = HtmlEncode;
                dynamicControl.DataFormatString = DataFormatString;
                dynamicControl.NullDisplayText = NullDisplayText;

                if (_convertEmptyStringToNull.HasValue)
                {
                    dynamicControl.ConvertEmptyStringToNull = ConvertEmptyStringToNull;
                }

                if (_applyFormatInEditMode.HasValue)
                {
                    dynamicControl.ApplyFormatInEditMode = ApplyFormatInEditMode;
                }

                cell.Controls.Add(dynamicControl);
            }
            else
            {
                base.InitializeCell(cell, columnIndex, inItem);
            }
        }


        [Category("Behavior"), DefaultValue(false)]
        public bool ConvertEmptyStringToNull
        {
            get
            {
                if (this._convertEmptyStringToNull.HasValue)
                {
                    return this._convertEmptyStringToNull.Value;
                }
                return false;
            }
            set
            {
                this._convertEmptyStringToNull = new bool?(value);
            }
        }

        [DefaultValue(""), Category("Behavior")]
        public virtual string DataField
        {
            get
            {
                if (this._dataField != null)
                {
                    return this._dataField;
                }
                object obj2 = base.ViewState["DataField"];
                if (obj2 != null)
                {
                    return (string)obj2;
                }
                return string.Empty;
            }
            set
            {
                if (!object.Equals(value, base.ViewState["DataField"]))
                {
                    base.ViewState["DataField"] = value;
                    this._dataField = value;
                    this.OnColumnChanged();
                }
            }
        }

        [Category("Data"), DefaultValue("")]
        public string DataFormatString
        {
            get
            {
                return (this._dataFormatString ?? string.Empty);
            }
            set
            {
                this._dataFormatString = value;
            }
        }

        private MetaColumn Column
        {
            get
            {
                if (base.DesignMode || (Owner == null))
                {
                    return null;
                }
                if (this._column == null)
                {
                    MetaTable table = Owner.OwnerGrid.FindMetaTable();
                    if (table == null)
                    {
                        throw new InvalidOperationException("");
                    }
                    this._column = table.GetColumn(this.DataField);
                }
                return this._column;
            }
        }

        public override string HeaderText
        {
            get
            {
                object obj2 = base.ViewState["HeaderText"];
                if (obj2 != null)
                {
                    return (string)obj2;
                }
                if (this.Column != null)
                {
                    return this.Column.DisplayName;
                }
                return this.DataField;
            }
            set
            {
                base.HeaderText = value;
            }
        }

        [DefaultValue(true), Category("Behavior")]
        public bool HtmlEncode
        {
            get
            {
                return this._htmlEncode;
            }
            set
            {
                this._htmlEncode = value;
            }
        }

        [Category("Behavior"), DefaultValue("")]
        public string NullDisplayText
        {
            get
            {
                return (this._nullDisplayText ?? string.Empty);
            }
            set
            {
                this._nullDisplayText = value;
            }
        }

        public override string SortExpression
        {
            get
            {
                object obj2 = base.ViewState["SortExpression"];
                if (obj2 != null)
                {
                    return (string)obj2;
                }
                if (this.Column != null)
                {
                    return this.Column.SortExpression;
                }
                return string.Empty;
            }
        }

        [DefaultValue(""), Category("Behavior")]
        public virtual string UIHint
        {
            get
            {
                object obj2 = base.ViewState["UIHint"];
                if (obj2 != null)
                {
                    return (string)obj2;
                }
                return string.Empty;
            }
            set
            {
                if (!object.Equals(value, base.ViewState["UIHint"]))
                {
                    base.ViewState["UIHint"] = value;
                    this.OnColumnChanged();
                }
            }
        }

        [Category("Behavior"), DefaultValue(false)]
        public bool ApplyFormatInEditMode
        {
            get
            {
                if (this._applyFormatInEditMode.HasValue)
                {
                    return this._applyFormatInEditMode.Value;
                }
                return false;
            }
            set
            {
                this._applyFormatInEditMode = new bool?(value);
            }
        }

        public override GridColumn Clone()
        {
            DynamicGridBoundColumn column = new DynamicGridBoundColumn();
            column.CopyBaseProperties(this);

            return column;
        }

        protected override void CopyBaseProperties(GridColumn fromColumn)
        {
            base.CopyBaseProperties(fromColumn);
            DynamicGridBoundColumn source = (DynamicGridBoundColumn)fromColumn;

            ConvertEmptyStringToNull = source.ConvertEmptyStringToNull;
            DataFormatString = source.DataFormatString;
            UIHint = source.UIHint;
            HtmlEncode = source.HtmlEncode;
            NullDisplayText = source.NullDisplayText;
            ApplyFormatInEditMode = source.ApplyFormatInEditMode;
        }

    }
}