using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace ServerControl1
{
    [DefaultProperty("Text")]
    [ToolboxData("<{0}:TemplatedControl runat=server></{0}:TemplatedControl>")]
    public class TemplatedControl : WebControl
    {
        private string _name;
        private string _text;

        private Message _message;
        private ITemplate _messageTemplate;

        [Browsable(false)]
        public Message Message
        {
            get
            {
                return _message;
            }
        }

        [PersistenceMode(PersistenceMode.InnerProperty)]
        [TemplateContainer(typeof(Message))]
        public virtual ITemplate MessageTemplate
        {
            get { return _messageTemplate; }
            set { _messageTemplate = value; }
        }

        [Bindable(true)]
        [DefaultValue("")]
        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }

        [Bindable(true)]
        [DefaultValue("")]
        public string Text
        {
            get { return _text; }
            set { _text = value; }
        }

        public override void DataBind()
        {
            EnsureChildControls();
            ChildControlsCreated = true;

            base.DataBind();
        }

        protected override void CreateChildControls()
        {
            this.Controls.Clear();

            _message = new Message(Name,Text);

            if (this.MessageTemplate == null)
            {
                this.MessageTemplate = new DefaultMessageTemplate();
            }

            this.MessageTemplate.InstantiateIn(_message);
            Controls.Add(_message);
        }

        protected override void RenderContents(HtmlTextWriter writer)
        {
            EnsureChildControls();
            ChildControlsCreated = true;

            base.RenderContents(writer);
        }

    }
}
