Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Text
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls

<DefaultProperty("Text")> _
<ToolboxData("<{0}:TemplatedControl runat=server></{0}:TemplatedControl>")> _
Public Class TemplatedControl
    Inherits System.Web.UI.WebControls.WebControl

    Private _name As String
    Private _text As String

    Private _message As Message
    Private _messageTemplate As ITemplate

    <Browsable(False)> Public ReadOnly Property Message() As Message
        Get
            Return _message
        End Get
    End Property

    <PersistenceMode(PersistenceMode.InnerProperty), _
        TemplateContainer(GetType(Message))> _
    Public Property MessageTemplate() As ITemplate
        Get
            Return _messageTemplate
        End Get
        Set(ByVal value As ITemplate)
            _messageTemplate = value
        End Set
    End Property

    <Bindable(True), DefaultValue("")> Public Property Name() As String
        Get
            Return _name
        End Get
        Set(ByVal value As String)
            _name = value
        End Set
    End Property

    <Bindable(True), DefaultValue("")> Public Property Text() As String
        Get
            Return _text
        End Get
        Set(ByVal value As String)
            _text = value
        End Set
    End Property

    Public Overrides Sub DataBind()
        CreateChildControls()
        ChildControlsCreated = True

        MyBase.DataBind()
    End Sub

    Protected Overrides Sub CreateChildControls()

        Me.Controls.Clear()

        _message = New Message(Name, Text)

        If Me.MessageTemplate Is Nothing Then
            Me.MessageTemplate = New DefaultMessageTemplate()
        End If

        Me.MessageTemplate.InstantiateIn(_message)
        Controls.Add(_message)
    End Sub

    Protected Overrides Sub RenderContents( _
        ByVal writer As System.Web.UI.HtmlTextWriter)

        EnsureChildControls()
        ChildControlsCreated = True

        MyBase.RenderContents(writer)
    End Sub

End Class
