Imports Microsoft.VisualBasic
Imports System
Imports System.Data
Imports System.Configuration
Imports System.Linq
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.HtmlControls
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Xml.Linq
Imports Telerik.Web.UI
Imports System.Collections
Imports System.Web.DynamicData
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Globalization
Imports System.Collections.Specialized


Namespace Telerik.Web.UI.DynamicData


    <ControlValueProperty("DataKeySelectedValue")> _
    Public Class DynamicRadGrid
        Inherits RadGrid
        Implements IControlParameterTarget
        Implements IPersistedSelector

        'Implements IPersistedSelector

        Public Sub New()
        End Sub

        Private selectedIndex As String = Nothing

        Protected Overloads Overrides Sub OnLoad(ByVal e As EventArgs)
            If SelectedIndexes.Count > 0 Then
                selectedIndex = SelectedIndexes(0)
            End If

            MyBase.OnLoad(e)
        End Sub

        Protected Overloads Overrides Sub OnDataBound(ByVal e As EventArgs)
            MyBase.OnDataBound(e)

            If Not selectedIndex Is Nothing Then
                Dim item As GridItem = Items(selectedIndex)
                If Not item Is Nothing Then
                    item.Selected = True
                End If
            Else
                If Items.Count > 0 Then
                    Items(0).Selected = True
                End If
            End If
        End Sub

        <Browsable(False)> _
        Public ReadOnly Property DataKeySelectedValue() As Object
            Get
                If Not Me.DataKey Is Nothing Then
                    Return Me.DataKey.Value
                End If

                Return SelectedValue
            End Get
        End Property

        Private _dataKey As System.Web.UI.WebControls.DataKey
        Public Property DataKey() As System.Web.UI.WebControls.DataKey
            Get
                Return _dataKey
            End Get
            Set(ByVal value As System.Web.UI.WebControls.DataKey)
                _dataKey = value
                If Not _dataKey Is Nothing Then
                    DirectCast(_dataKey, IStateManager).TrackViewState()
                End If
            End Set
        End Property

        '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 Overloads Overrides Sub OnInit(ByVal e As EventArgs)
            MyBase.OnInit(e)

            AllowAutomaticUpdates = True
            AllowAutomaticDeletes = True

            Dim metaTable As MetaTable = Me.FindMetaTable()

            Dim list As New List(Of String)()
            For Each column As MetaColumn In metaTable.PrimaryKeyColumns
                list.Add(column.Name)
            Next
            MasterTableView.DataKeyNames = list.ToArray()

            For Each column As MetaColumn In metaTable.Columns
                If Not column.Scaffold OrElse column.IsLongString OrElse TypeOf column Is MetaChildrenColumn Then
                    Continue For
                End If

                Dim gridColumn As 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)
            Next
        End Sub

        Public Function GetPropertyNameExpression(ByVal columnName As String) As String
            Return "DataKeySelectedValue"
        End Function

        ReadOnly Property Table() As MetaTable Implements IControlParameterTarget.Table
            Get
                Return Me.FindMetaTable()
            End Get
        End Property

        Public Overridable ReadOnly Property FilteredColumn() As MetaColumn
            Get
                Return Nothing
            End Get
        End Property

        Public ReadOnly Property FilteredColumn1() As System.Web.DynamicData.MetaColumn Implements System.Web.DynamicData.IControlParameterTarget.FilteredColumn
            Get

            End Get
        End Property

        Public Function GetPropertyNameExpression1(ByVal columnName As String) As String Implements System.Web.DynamicData.IControlParameterTarget.GetPropertyNameExpression

        End Function

        Public Property DataKey1() As System.Web.UI.WebControls.DataKey Implements System.Web.UI.WebControls.IPersistedSelector.DataKey
            Get

            End Get
            Set(ByVal value As System.Web.UI.WebControls.DataKey)

            End Set
        End Property
    End Class

    Public Class DynamicGridBoundColumn
        Inherits GridBoundColumn
        Private _applyFormatInEditMode As System.Nullable(Of Boolean)
        Private _convertEmptyStringToNull As System.Nullable(Of Boolean)
        Private _dataField As String
        Private _dataFormatString As String
        Private _htmlEncode As Boolean = True
        Private _nullDisplayText As String
        Private _column As MetaColumn

        Public Overloads Overrides Sub FillValues(ByVal newValues As IDictionary, ByVal editableItem As GridEditableItem)
            Dim values As New OrderedDictionary()

            ExtractValuesFromBindableControls(values, editableItem)

            For Each entry As DictionaryEntry In values
                If Not newValues.Contains(entry.Key) Then
                    newValues.Add(entry.Key, entry.Value)
                End If
            Next
        End Sub

        Friend Shared Sub ExtractValuesFromBindableControls(ByVal dictionary As IOrderedDictionary, ByVal container As Control)
            Dim control As IBindableControl = TryCast(container, IBindableControl)
            If Not control Is Nothing Then
                control.ExtractValues(dictionary)
            End If
            For Each control2 As Control In container.Controls
                ExtractValuesFromBindableControls(dictionary, control2)
            Next
        End Sub

        Public Overloads Overrides Sub InitializeCell(ByVal cell As TableCell, ByVal columnIndex As Integer, ByVal inItem As GridItem)
            If TypeOf inItem Is GridEditableItem Then
                Dim dynamicControl As New DynamicControl()
                dynamicControl.DataField = DataField

                Dim isInsert As Boolean = TypeOf inItem Is GridEditFormInsertItem OrElse TypeOf inItem Is GridDataInsertItem

                If isInsert Then
                    dynamicControl.Mode = DataBoundControlMode.Insert
                End If

                If inItem.IsInEditMode Then
                    dynamicControl.Mode = DataBoundControlMode.Edit
                End If

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

                If _convertEmptyStringToNull.HasValue Then
                    dynamicControl.ConvertEmptyStringToNull = ConvertEmptyStringToNull
                End If

                If _applyFormatInEditMode.HasValue Then
                    dynamicControl.ApplyFormatInEditMode = ApplyFormatInEditMode
                End If

                cell.Controls.Add(dynamicControl)
            Else
                MyBase.InitializeCell(cell, columnIndex, inItem)
            End If
        End Sub


        <Category("Behavior"), DefaultValue(False)> _
        Public Overloads Property ConvertEmptyStringToNull() As Boolean
            Get
                If Me._convertEmptyStringToNull.HasValue Then
                    Return Me._convertEmptyStringToNull.Value
                End If
                Return False
            End Get
            Set(ByVal value As Boolean)
                Me._convertEmptyStringToNull = New System.Nullable(Of Boolean)(value)
            End Set
        End Property

        <DefaultValue(""), Category("Behavior")> _
        Public Overloads Overrides Property DataField() As String
            Get
                If Not Me._dataField Is Nothing Then
                    Return Me._dataField
                End If
                Dim obj2 As Object = MyBase.ViewState("DataField")
                If Not obj2 Is Nothing Then
                    Return DirectCast(obj2, String)
                End If
                Return String.Empty
            End Get
            Set(ByVal value As String)
                If Not Object.Equals(value, MyBase.ViewState("DataField")) Then
                    MyBase.ViewState("DataField") = value
                    Me._dataField = value
                    Me.OnColumnChanged()
                End If
            End Set
        End Property

        <Category("Data"), DefaultValue("")> _
        Public Overloads Overrides Property DataFormatString() As String
            Get
                Return (If(Me._dataFormatString, String.Empty))
            End Get
            Set(ByVal value As String)
                Me._dataFormatString = value
            End Set
        End Property

        Private ReadOnly Property Column() As MetaColumn
            Get
                If MyBase.DesignMode OrElse (Owner Is Nothing) Then
                    Return Nothing
                End If
                If Me._column Is Nothing Then
                    Dim table As MetaTable = Owner.OwnerGrid.FindMetaTable()
                    If table Is Nothing Then
                        Throw New InvalidOperationException("")
                    End If
                    Me._column = table.GetColumn(Me.DataField)
                End If
                Return Me._column
            End Get
        End Property

        Public Overloads Overrides Property HeaderText() As String
            Get
                Dim obj2 As Object = MyBase.ViewState("HeaderText")
                If Not obj2 Is Nothing Then
                    Return DirectCast(obj2, String)
                End If
                If Me.Column IsNot Nothing Then
                    Return Me.Column.DisplayName
                End If
                Return Me.DataField
            End Get
            Set(ByVal value As String)
                MyBase.HeaderText = value
            End Set
        End Property

        <DefaultValue(True), Category("Behavior")> _
        Public Overloads Overrides Property HtmlEncode() As Boolean
            Get
                Return Me._htmlEncode
            End Get
            Set(ByVal value As Boolean)
                Me._htmlEncode = value
            End Set
        End Property

        <Category("Behavior"), DefaultValue("")> _
        Public Property NullDisplayText() As String
            Get
                Return (If(Me._nullDisplayText, String.Empty))
            End Get
            Set(ByVal value As String)
                Me._nullDisplayText = value
            End Set
        End Property

        Public Overloads ReadOnly Property SortExpression() As String
            Get
                Dim obj2 As Object = MyBase.ViewState("SortExpression")
                If Not obj2 Is Nothing Then
                    Return DirectCast(obj2, String)
                End If
                If Not Me.Column Is Nothing Then
                    Return Me.Column.SortExpression
                End If
                Return String.Empty
            End Get
        End Property

        <DefaultValue(""), Category("Behavior")> _
        Public Overridable Property UIHint() As String
            Get
                Dim obj2 As Object = MyBase.ViewState("UIHint")
                If Not obj2 Is Nothing Then
                    Return DirectCast(obj2, String)
                End If
                Return String.Empty
            End Get
            Set(ByVal value As String)
                If Not Object.Equals(value, MyBase.ViewState("UIHint")) Then
                    MyBase.ViewState("UIHint") = value
                    Me.OnColumnChanged()
                End If
            End Set
        End Property

        <Category("Behavior"), DefaultValue(False)> _
        Public Property ApplyFormatInEditMode() As Boolean
            Get
                If Me._applyFormatInEditMode.HasValue Then
                    Return Me._applyFormatInEditMode.Value
                End If
                Return False
            End Get
            Set(ByVal value As Boolean)
                Me._applyFormatInEditMode = New System.Nullable(Of Boolean)(value)
            End Set
        End Property

        Public Overloads Overrides Function Clone() As GridColumn
            Dim column As New DynamicGridBoundColumn()
            column.CopyBaseProperties(Me)

            Return column
        End Function

        Protected Overloads Overrides Sub CopyBaseProperties(ByVal fromColumn As GridColumn)
            MyBase.CopyBaseProperties(fromColumn)
            Dim source As DynamicGridBoundColumn = DirectCast(fromColumn, DynamicGridBoundColumn)

            ConvertEmptyStringToNull = source.ConvertEmptyStringToNull
            DataFormatString = source.DataFormatString
            UIHint = source.UIHint
            HtmlEncode = source.HtmlEncode
            NullDisplayText = source.NullDisplayText
            ApplyFormatInEditMode = source.ApplyFormatInEditMode
        End Sub

    End Class

End Namespace

