using System;
using System.Drawing;
using System.Security.Permissions;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.Util;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

namespace CustomControls
{
    public class StateControl : CompositeControl
    {
        private List<string> stringList = null;
        private int selectedIndex = -1;
        private Table mainTable = null;

        public List<string> DataSource
        {
            get 
            {
                if (stringList == null)
                    stringList = (List<string>)ViewState["stringList"];
                return stringList;
            }
            set 
            {
                stringList = value;
                ViewState["stringList"] = value;
            }
        }
        
        public int SelectedIndex
        {
            get { return selectedIndex; }
            set { selectedIndex = value; }
        }

        public override void DataBind()
        {
            base.DataBind();
            EnsureChildControls();
            for (int x = 0; x < DataSource.Count; x++)
            {
                TableRow tr = new TableRow();
                if (selectedIndex == x)
                    tr.BackColor = Color.White;
                else
                    tr.BackColor = Color.White;

                TableCell td = new TableCell();
                td.Text = DataSource[x];
                tr.Cells.Add(td);
                mainTable.Rows.Add(tr);
            }
        }

        protected override void LoadControlState(object savedState)
        {
            Page.Response.Write("WczytanyStanKontrolki: " + savedState.ToString() + "<br/>");
            selectedIndex = (int)savedState;
        }

        protected override object SaveControlState()
        {
            Page.Response.Write("ZapisywanyStanKontrolki: " + selectedIndex.ToString()+"<br/>");
            return selectedIndex;
        }

        protected override void RenderContents(HtmlTextWriter writer)
        {
            base.RenderContents(writer);
        }

        protected override void CreateChildControls()
        {
            Page.RegisterRequiresControlState(this);
            mainTable = new Table();
            mainTable.Width = new Unit(100, UnitType.Percentage);
            Controls.Add(mainTable);
        }
    }
}
