using System;
using System.Data;
using System.Collections;
using System.ComponentModel;
using System.Security.Permissions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
[assembly: TagPrefix("CustomCompositeControl", "Custom")]
   
namespace CustomCompositeControl
{


    [AspNetHostingPermission(SecurityAction.Demand,
       Level = AspNetHostingPermissionLevel.Minimal)]
    [AspNetHostingPermission(SecurityAction.InheritanceDemand,
        Level = AspNetHostingPermissionLevel.Minimal),
      DefaultProperty("DataTextField"),
      ToolboxData("<{0}:TreeViewCompositeControl runat=\"server\"> </{0}:TreeViewCompositeControl>")]
    public class TreeViewCompositeControl : DataBoundControl
    {
        string _idTreeView;
        string _cssclass;
        TreeViewReport _treeviewcontrolstate;

        public TreeViewCompositeControl()
        {
            _idTreeView = "MyTreeView1";
            _cssclass = "stateTitle";
        }

        public string DataTextField
        {
            get
            {
                object o = ViewState["DataTextField"];
                return ((o == null) ? string.Empty : (string)o);
            }
            set
            {
                ViewState["DataTextField"] = value;
                if (Initialized)
                {
                    OnDataPropertyChanged();
                }
            }
        }

        
        public string IDTreeView
        {
            get
            {
               return _idTreeView;
            }
            set
            {
                _idTreeView = value;
            }
        }


        public ArrayList RetrievedDataPostBack
        {
            get
            {
                ArrayList o = (ArrayList)ViewState["RetrievedDataPostBack"];
                return o;
            }
            set
            {
                ViewState["RetrievedDataPostBack"] = value;
                
            }
        }
        
        protected override void PerformSelect()
        {
            // Call OnDataBinding here if bound to a data source using the
            // DataSource property (instead of a DataSourceID), because the
            // databinding statement is evaluated before the call to GetData.       
            if (!IsBoundUsingDataSourceID)
            {
                this.OnDataBinding(EventArgs.Empty);
            }

            // The GetData method retrieves the DataSourceView object from  
            // the IDataSource associated with the data-bound control.            
            GetData().Select(CreateDataSourceSelectArguments(),
                this.OnDataSourceViewSelectCallback);

            // The PerformDataBinding method has completed.
            RequiresDataBinding = false;
            MarkAsDataBound();

            // Raise the DataBound event.
            OnDataBound(EventArgs.Empty);
        }

        private void OnDataSourceViewSelectCallback(IEnumerable retrievedData)
        {
            //IEnumerable retrievedDataPostBack = null;
            // Call OnDataBinding only if it has not already been 
            // called in the PerformSelect method.
            if (IsBoundUsingDataSourceID)
            {
                OnDataBinding(EventArgs.Empty);
            }
            // The PerformDataBinding method binds the data in the  
            // retrievedData collection to elements of the data-bound control.

            //if (RetrievedDataPostBack == null)
            //{
                RetrievedDataPostBack = setRetrievedDataPostBack(retrievedData);
                //retrievedDataPostBack = RetrievedDataPostBack;
            //}
            //else
            //{
            //    retrievedDataPostBack = RetrievedDataPostBack;
            //}

            PerformDataBinding(RetrievedDataPostBack);
        }

        protected override void PerformDataBinding(IEnumerable retrievedData)
        {
            base.PerformDataBinding(retrievedData);

            // Verify data exists.
            if (retrievedData != null)
            {
                TreeViewReport treeview = new TreeViewReport(_idTreeView);
                treeview.RootNodeStyle.CssClass = _cssclass;
                treeview.ShowExpandCollapse = false;
                treeview.ID = _idTreeView;

                treeview.CreateTreeView(retrievedData);

                //this.TreeViewControlState = treeview;
                
                this.Controls.Add(treeview);
            }
        }

        private ArrayList setRetrievedDataPostBack(IEnumerable retrievedData)
        {
            CustomDataItem dataItem;
            ArrayList array = new ArrayList();
            
            foreach (DataRowView rvw in ((DataView)retrievedData))
            {
                dataItem = new CustomDataItem();
                if (rvw["Descrizione"] != DBNull.Value)
                    dataItem.Descrizione = rvw["Descrizione"].ToString();

                if (rvw["IdSezione"] != DBNull.Value)
                 dataItem.IdSezione = rvw["IdSezione"].ToString();

                if (rvw["InternalSectionCode"] != DBNull.Value)
                    dataItem.InternalSectionCode = rvw["InternalSectionCode"].ToString();

                if (rvw["IsDefault"] != DBNull.Value)
                    dataItem.IsDefault = Convert.ToBoolean(rvw["IsDefault"]);

                if (rvw["IsMandatory"] == DBNull.Value)
                    dataItem.IsMandatory = false;
                else
                    dataItem.IsMandatory = Convert.ToBoolean(rvw["IsMandatory"]);

                if (rvw["Livello"] != DBNull.Value)
                    dataItem.Livello = Convert.ToInt32(rvw["Livello"]);

                if (rvw["NomeControlloGruppo"] != DBNull.Value)
                    dataItem.NomeControlloGruppo = rvw["NomeControlloGruppo"].ToString();

                if (rvw["TpSezione"] != DBNull.Value)
                    dataItem.TpSezione = Convert.ToInt32(rvw["TpSezione"]);


                // Sezione Personalizzata
                if (rvw["SezionePers"] != DBNull.Value)
                    dataItem.SezionePersonalizzata = Convert.ToBoolean(rvw["SezionePers"]);

                // Sezione Immagine
                if (rvw["NomeImmagine"] == DBNull.Value)
                    dataItem.Image = "";
                else
                    dataItem.Image = rvw["NomeImmagine"].ToString();

                if (rvw["CSSClass"] == DBNull.Value)
                    dataItem.CSSClassName = "";
                else
                    dataItem.CSSClassName = rvw["CSSClass"].ToString();

                // NoParentBehaviour
                if (rvw["NoParentBehaviour"] != DBNull.Value)
                    dataItem.NoParentBehaviour = Convert.ToBoolean(rvw["NoParentBehaviour"]);

                // NoParentBehaviour
                if (rvw["NoCheckedByParent"] != DBNull.Value)
                    dataItem.NoCheckedByParent = Convert.ToInt16(rvw["NoCheckedByParent"]);
              
                   
                // IsSectionPrinting
                if (rvw["IsSectionPrinting"] != DBNull.Value)
                    dataItem.IsSectionPrinting = Convert.ToBoolean(rvw["IsSectionPrinting"]);

                // Tipo controllo
                dataItem.TipoControllo = getTipoControllo(dataItem.TpSezione);

                array.Add(dataItem);
            }
            return array;
        }

     
        private TipoControllo getTipoControllo(int TpSezione)
        {
            TipoControllo tpc;
            switch (TpSezione)
            {
                 case 0:
                     tpc = TipoControllo.MenuRoot;
                    break;
                case 1:
                    tpc = TipoControllo.CheckBox;
                    break;
                case 2:
                    tpc = TipoControllo.RadioButton;
                    break;
                case 3:
                    tpc = TipoControllo.Label;
                    break;
                default:
                    tpc = TipoControllo.CheckBox;
                    break;
            }

            return tpc;
        }

    }
}