using Microsoft.VisualBasic;
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using BaseClasses;
using BaseClasses.Data;
using BaseClasses.Utils;
using BaseClasses.Web.UI.WebControls;

namespace SelectedDatesExample.UI.Controls.LargeListSelector
{
    public class ItemsTableRecordControl : BaseItemsTableRecordControl
    {
    }
    public class ItemsTable : BaseItemsTable
    {
    }
    public class BaseItemsTableRecordControl : SelectedDatesExample.UI.BaseApplicationRecordControl
    {
        public BaseItemsTableRecordControl()
        {
            this.Init += new EventHandler(Control_Init);
            this.Load += new EventHandler(Control_Load);
        }

        protected virtual void Control_Init(object sender, System.EventArgs e)
        {
            this.SelectButton.Click += new EventHandler(SelectButton_Click);
        }

        protected virtual void Control_Load(object sender, System.EventArgs e)
        {
        }

        public override void DataBind()
        {
            if (this.DataSource == null)
            {
                return;
            }
            ItemsTable table = ((ItemsTable)(this.Page.FindControlRecursively("ItemsTable")));
            BaseClasses.Data.TableDefinition td = table.GetTable().TableDefinition;
            BaseClasses.Data.BaseColumn col = td.ColumnList.GetByAnyName(table.Field);
            BaseClasses.Data.BaseColumn displayCol = td.ColumnList.GetByAnyName(table.DisplayField);
            this.ValueText.Text = this.DataSource.GetValue(col).ToString();
            this.ItemText.Text = this.DataSource.Format(displayCol);
        }

        public virtual void LoadData()
        {
        }

        protected virtual void SelectButton_Click(object sender, EventArgs args)
        {
            ItemsTable table = ((ItemsTable)(this.Page.FindControlRecursively("ItemsTable")));
            BaseClasses.Data.TableDefinition td = table.GetTable().TableDefinition;
            BaseClasses.Data.BaseColumn col = td.ColumnList.GetByAnyName(table.Field);
            BaseClasses.Data.BaseColumn displayCol = td.ColumnList.GetByAnyName(table.DisplayField);
            this.RegisterSelectValueScript(table.Target, this.ValueText.Text, this.ItemText.Text);
        }

        protected override void LoadViewState(object savedState)
        {
            base.LoadViewState(savedState);
        }

        protected override object SaveViewState()
        {
            return base.SaveViewState();
        }

        private BaseRecord _DataSource;
        public BaseRecord DataSource
        {
            get
            {
                return this._DataSource;
            }
            set
            {
                this._DataSource = value;
            }
        }

        public System.Web.UI.WebControls.Label ValueText
        {
            get
            {
                return ((System.Web.UI.WebControls.Label)(MiscUtils.FindControlRecursively(this, "ValueText")));
            }
        }

        public System.Web.UI.WebControls.LinkButton SelectButton
        {
            get
            {
                return ((System.Web.UI.WebControls.LinkButton)(MiscUtils.FindControlRecursively(this, "SelectButton")));
            }
        }

        public System.Web.UI.WebControls.Label ItemText
        {
            get
            {
                return ((System.Web.UI.WebControls.Label)(MiscUtils.FindControlRecursively(this, "ItemText")));
            }
        }

        public new BaseApplicationPage Page
        {
            get
            {
                return ((BaseApplicationPage)(base.Page));
            }
        }

        private void RegisterSelectValueScript(string target, string value, string text)
        {
            string scriptContent = string.Format("updateTarget({0}, {1}, {2});", BaseClasses.Web.AspxTextWriter.CreateJScriptStringLiteral(target), BaseClasses.Web.AspxTextWriter.CreateJScriptStringLiteral(value), BaseClasses.Web.AspxTextWriter.CreateJScriptStringLiteral(text));
            string script = BaseClasses.Web.AspxTextWriter.CreateJScriptBlock(scriptContent);
            this.Page.ClientScript.RegisterStartupScript(typeof(string), "SelectValueScript", script);
        }
    }
    public class BaseItemsTable : SelectedDatesExample.UI.BaseApplicationTableControl
    {
		public BaseItemsTable()
		{
			this.Load += new EventHandler(Control_Load);
			this.Init += new EventHandler(Control_Init);
			this.PreRender += new EventHandler(Control_PreRender);
		}

        protected virtual void Control_Init(object sender, System.EventArgs e)
        {
            this.Pagination.FirstPage.Click += new ImageClickEventHandler(Pagination_FirstPage_Click);
            this.Pagination.LastPage.Click += new ImageClickEventHandler(Pagination_LastPage_Click);
            this.Pagination.NextPage.Click += new ImageClickEventHandler(Pagination_NextPage_Click);
            this.Pagination.PageSizeButton.Button.Click += new EventHandler(Pagination_PageSizeButton_Click);
            this.Pagination.PreviousPage.Click += new ImageClickEventHandler(Pagination_PreviousPage_Click);
            this.SearchButton.Button.Click += new EventHandler(SearchButton_Click);
            if (!(this.Page.IsPostBack))
            {
                this.CurrentSortOrder = new OrderBy(true, true);
                this.PageSize = 10;
                this.PageIndex = 0;
            }
        }

        protected virtual void Control_Load(object sender, System.EventArgs e)
        {
            this.RegisterAutoCloseScript();
            try
            {
                if ((!(this.Page.IsPostBack)))
                {
                    DbUtils.StartTransaction();
                    this.LoadData();
                    this.DataBind();
                }
            }
            catch (Exception ex)
            {
                MiscUtils.RegisterJScriptAlert(this, "Load_Error_Message", ex.Message);
            }
            finally
            {
                if (!(this.Page.IsPostBack))
                {
                    DbUtils.EndTransaction();
                }
            }
        }

        public virtual void LoadData()
        {
            string tableStr = NetUtils.GetUrlParam(this, "Table", true);
            string fieldStr = NetUtils.GetUrlParam(this, "Field", true);
            string targetStr = NetUtils.GetUrlParam(this, "Target", true);
            string displayFieldStr = NetUtils.GetUrlParam(this, "DisplayField", true);

            if ((tableStr == null || tableStr.Length == 0) || 
                (fieldStr == null || fieldStr.Length == 0) || 
                (targetStr == null || targetStr.Length == 0) || 
                (displayFieldStr == null || displayFieldStr.Length == 0))
            {
                this.DataSource = ((BaseRecord[])((new ArrayList()).ToArray(Type.GetType(System.Reflection.Assembly.CreateQualifiedName("BaseClasses","BaseClasses.Data.BaseRecord")))));
                return;
            }

            WhereClause whereClause = CreateWhereClause();
            OrderBy orderBy = CreateOrderBy();
            
            this.SetPagintionPageSize();
            
            this.TotalRecords = System.Convert.ToInt32(this.GetTable().GetRecordListCount(whereClause.GetFilter(), null));
            if (this.TotalPages <= 0)
            {
                this.PageIndex = 0;
            }
            else if (this.DisplayLastPage || this.PageIndex >= this.TotalPages)
            {
                this.PageIndex = this.TotalPages - 1;
            }
            
            this.DataSource = ((BaseRecord[])(this.GetTable().GetRecordList(whereClause.GetFilter(), orderBy, this.PageIndex, this.PageSize).ToArray(Type.GetType(System.Reflection.Assembly.CreateQualifiedName("BaseClasses","BaseClasses.Data.BaseRecord")))));
        }

        public override void DataBind()
        {
            base.DataBind();
            if (this.DataSource == null)
            {
                return;
            }
            BindPaginationControls();
            System.Web.UI.WebControls.Repeater rep = ((System.Web.UI.WebControls.Repeater)(this.FindControl("row1")));
            rep.DataSource = this.DataSource;
            rep.DataBind();

            int index = 0;
            foreach (System.Web.UI.WebControls.RepeaterItem repItem in rep.Items)
            {
                ItemsTableRecordControl recControl = ((ItemsTableRecordControl)(repItem.FindControl("ItemsTableRecordControl")));
                recControl.DataSource = this.DataSource[index];
                recControl.DataBind();
                index += 1;
            }
        }

        protected virtual void BindPaginationControls()
        {
            this.Pagination.FirstPage.Enabled = !((this.PageIndex == 0));
            this.Pagination.LastPage.Enabled = !((this.PageIndex == this.TotalPages - 1));
            this.Pagination.NextPage.Enabled = !((this.PageIndex == this.TotalPages - 1));
            this.Pagination.PreviousPage.Enabled = !((this.PageIndex == 0));
            this.Pagination.CurrentPage.Text = (this.PageIndex + 1).ToString();
            this.Pagination.PageSize.Text = this.PageSize.ToString();
            this.Pagination.TotalItems.Text = this.TotalRecords.ToString();
            this.Pagination.TotalPages.Text = this.TotalPages.ToString();
        }

        protected virtual void SetPagintionPageSize()
        {
            try
            {
                if (this.Pagination.PageSize != null &&
                    this.Pagination.PageSize.Text != null &&
                    this.Pagination.PageSize.Text.Length > 0)
                {
                    this.PageSize = int.Parse(this.Pagination.PageSize.Text);
                }
            }
            catch (Exception ex)
            {
            }
        }

        protected virtual OrderBy CreateOrderBy()
        {
            BaseColumn col = this.GetTable().TableDefinition.ColumnList.GetByAnyName(this.DisplayField);
            if (col != null && this.CurrentSortOrder.Find(col) == null)
            {
                this.CurrentSortOrder.Add(col, OrderByItem.OrderDir.Asc);
            }
            return this.CurrentSortOrder;
        }

        protected virtual WhereClause CreateWhereClause()
        {
            WhereClause whereClause = new WhereClause();
            BaseClasses.Data.BaseColumn displayCol = this.GetTable().TableDefinition.ColumnList.GetByAnyName(this.DisplayField);
            if (MiscUtils.IsValueSelected(this.StartsWith))
            {
                whereClause.iAND(displayCol, BaseFilter.ComparisonOperator.Starts_With, this.StartsWith.Text, true, true);
            }
            if (MiscUtils.IsValueSelected(this.Contains))
            {
                whereClause.iAND(displayCol, BaseFilter.ComparisonOperator.Contains, this.Contains.Text, true, true);
            }
            return whereClause;
        }

        private void Control_PreRender(object sender, System.EventArgs e)
        {
            if (this.DataChanged)
            {
                try
                {
                    DbUtils.StartTransaction();
                    this.LoadData();
                    this.DataBind();
                }
                catch (Exception ex)
                {
                    MiscUtils.RegisterJScriptAlert(this, "Load_Error_Message", ex.Message);
                }
                finally
                {
                    DbUtils.EndTransaction();
                }
            }
        }

        protected override void LoadViewState(object savedState)
        {
            base.LoadViewState(savedState);
            string orderByStr = ((string)(ViewState["ItemsTable_OrderBy"]));
            if (!(orderByStr == null || orderByStr.Length > 0))
            {
                this.CurrentSortOrder = BaseClasses.Data.OrderBy.FromXmlString(orderByStr);
            }
            else
            {
                this.CurrentSortOrder = new OrderBy(true, true);
            }

            if (ViewState["Page_Index"] != null)
            {
                this.PageIndex = (int)ViewState["Page_Index"];
            }

            if (ViewState["Page_Size"] != null)
            {
                this.PageSize = (int)ViewState["Page_Size"];
            }
        }

        protected override object SaveViewState()
        {
            if (this.CurrentSortOrder != null)
            {
                this.ViewState["ItemsTable_OrderBy"] = this.CurrentSortOrder.ToXmlString();
            }
            this.ViewState["Page_Index"] = this.PageIndex;
            this.ViewState["Page_Size"] = this.PageSize;
            return base.SaveViewState();
        }

        public virtual void Pagination_FirstPage_Click(object sender, ImageClickEventArgs args)
        {
            try
            {
                this.PageIndex = 0;
                this.DataChanged = true;
            }
            catch (Exception ex)
            {
                MiscUtils.RegisterJScriptAlert(this, "BUTTON_CLICK_MESSAGE", ex.Message);
            }
            finally
            {
            }
        }

        public virtual void Pagination_LastPage_Click(object sender, ImageClickEventArgs args)
        {
            try
            {
                this.DisplayLastPage = true;
                this.DataChanged = true;
            }
            catch (Exception ex)
            {
                MiscUtils.RegisterJScriptAlert(this, "BUTTON_CLICK_MESSAGE", ex.Message);
            }
            finally
            {
            }
        }

        public virtual void Pagination_NextPage_Click(object sender, ImageClickEventArgs args)
        {
            try
            {
                this.PageIndex += 1;
                this.DataChanged = true;
            }
            catch (Exception ex)
            {
                MiscUtils.RegisterJScriptAlert(this, "BUTTON_CLICK_MESSAGE", ex.Message);
            }
            finally
            {
            }
        }

        public virtual void Pagination_PageSizeButton_Click(object sender, EventArgs args)
        {
            try
            {
                this.DataChanged = true;
            }
            catch (Exception ex)
            {
                MiscUtils.RegisterJScriptAlert(this, "BUTTON_CLICK_MESSAGE", ex.Message);
            }
            finally
            {
            }
        }

        public virtual void Pagination_PreviousPage_Click(object sender, ImageClickEventArgs args)
        {
            try
            {
                if (this.PageIndex > 0)
                {
                    this.PageIndex -= 1;
                    this.DataChanged = true;
                }
            }
            catch (Exception ex)
            {
                MiscUtils.RegisterJScriptAlert(this, "BUTTON_CLICK_MESSAGE", ex.Message);
            }
            finally
            {
            }
        }

        public virtual void SearchButton_Click(object sender, EventArgs args)
        {
            try
            {
                this.DataChanged = true;
            }
            catch (Exception ex)
            {
                MiscUtils.RegisterJScriptAlert(this, "BUTTON_CLICK_MESSAGE", ex.Message);
            }
            finally
            {
            }
        }

        private int _PageSize;
        public int PageSize
        {
            get
            {
                return this._PageSize;
            }
            set
            {
                this._PageSize = value;
            }
        }

        private int _PageIndex;
        public int PageIndex
        {
            get
            {
                return this._PageIndex;
            }
            set
            {
                this._PageIndex = value;
            }
        }

        private int _TotalRecords;
        public int TotalRecords
        {
            get
            {
                return this._TotalRecords;
            }
            set
            {
                if (this.PageSize > 0)
                {
					double num = this.PageSize;
					this.TotalPages = System.Convert.ToInt32(Math.Ceiling(Convert.ToDouble(value / num)));
				}
                this._TotalRecords = value;
            }
        }

        private int _TotalPages;
        public int TotalPages
        {
            get
            {
                return this._TotalPages;
            }
            set
            {
                this._TotalPages = value;
            }
        }


        private bool _DisplayLastPage;
        public bool DisplayLastPage
        {
            get
            {
                return this._DisplayLastPage;
            }
            set
            {
                this._DisplayLastPage = value;
            }
        }

        private bool _DataChanged = false;
        public bool DataChanged
        {
            get
            {
                return this._DataChanged;
            }
            set
            {
                this._DataChanged = value;
            }
        }

        private OrderBy _CurrentSortOrder = null;
        public OrderBy CurrentSortOrder
        {
            get
            {
                return this._CurrentSortOrder;
            }
            set
            {
                this._CurrentSortOrder = value;
            }
        }

        private BaseRecord[] _DataSource = null;
        public BaseRecord[] DataSource
        {
            get
            {
                return this._DataSource;
            }
            set
            {
                this._DataSource = value;
            }
        }

        public string Table
        {
            get
            {
                string errMsg;
                string TYPE_FORMAT = "{0}.{1}{2},{3}";
                string tableName = NetUtils.GetUrlParam(this, "Table", true);
				tableName = tableName.Replace(" ", "_");
                try
                {
                    string tableType = string.Format(TYPE_FORMAT, "SelectedDatesExample.Business", tableName, "Table", "App_Code");
                    Type.GetType(tableType, true, true);
                    return tableType;
                }
                catch (Exception ex)
                {
                    errMsg = ex.Message;
                }
                try
                {
                    string viewType = string.Format(TYPE_FORMAT, "SelectedDatesExample.Business", tableName, "View", "App_Code");
                    Type.GetType(viewType, true, true);
                    return viewType;
                }
                catch (Exception ex)
                {
                    errMsg = ex.Message;
                }
                try
                {
                    string queryType = string.Format(TYPE_FORMAT, "SelectedDatesExample.Business", tableName, "Query", "App_Code");
                    Type.GetType(queryType, true, true);
                    return queryType;
                }
                catch (Exception ex)
                {
                    errMsg = ex.Message;
                }
                return "";
            }
        }

        public string Field
        {
            get
            {
                return NetUtils.GetUrlParam(this, "Field", true);
            }
        }

        public string DisplayField
        {
            get
            {
                return NetUtils.GetUrlParam(this, "DisplayField", true);
            }
        }

        public string Target
        {
            get
            {
                return NetUtils.GetUrlParam(this, "Target", true);
            }
        }

        public System.Web.UI.WebControls.TextBox StartsWith
        {
            get
            {
                return ((System.Web.UI.WebControls.TextBox)(MiscUtils.FindControlRecursively(this, "StartsWith")));
            }
        }

        public System.Web.UI.WebControls.TextBox Contains
        {
            get
            {
                return ((System.Web.UI.WebControls.TextBox)(MiscUtils.FindControlRecursively(this, "Contains")));
            }
        }

        public SelectedDatesExample.UI.IThemeButton SearchButton
        {
            get
            {
                return ((SelectedDatesExample.UI.IThemeButton)(MiscUtils.FindControlRecursively(this, "SearchButton")));
            }
        }

        public SelectedDatesExample.UI.IPagination Pagination
        {
            get
            {
                return ((SelectedDatesExample.UI.IPagination)(MiscUtils.FindControlRecursively(this, "Pagination")));
            }
        }

        public override string ModifyRedirectUrl(string url, string arg)
        {
            return ModifyRedirectUrl(url, arg, null);
        }

        public ItemsTableRecordControl[] GetRecordControls()
        {
            ArrayList recList = new ArrayList();
            System.Web.UI.WebControls.Repeater rep = ((System.Web.UI.WebControls.Repeater)(this.FindControl("row1")));

            foreach (System.Web.UI.WebControls.RepeaterItem repItem in rep.Items)
            {
                ItemsTableRecordControl recControl = ((ItemsTableRecordControl)(repItem.FindControl("ItemsTableRecordControl")));
                recList.Add(recControl);
            }
            return ((ItemsTableRecordControl[])(recList.ToArray(Type.GetType("SelectedDatesExample.UI.Controls.LargeListSelector.ItemsTableRecordControl"))));
        }

        public new BaseApplicationPage Page
        {
            get
            {
                return ((BaseApplicationPage)(base.Page));
            }
        }

        private void RegisterAutoCloseScript()
        {
            if ((StringUtils.InvariantUCase(this.Page.Request.Browser.Browser).IndexOf("IE") < 0))
            {
                return;
            }
            if ((this.Page.Request.Browser.MajorVersion < 5))
            {
                return;
            }
            string script = BaseClasses.Web.AspxTextWriter.CreateJScriptBlock("function onParentUnload() { window.close(); }" + "\r\n" + "if (window.opener && !window.opener.closed) { window.opener.attachEvent('onunload', onParentUnload);}");
            this.Page.ClientScript.RegisterClientScriptBlock(typeof(string), "AutoCloseScript", script);
        }

        public BaseClasses.Data.BaseTable GetTable()
        {
            string tn = this.Table;
            try
            {
                return BaseClasses.Data.BaseTable.CreateInstance(tn);
            }
            catch (System.Exception e)
            {
                tn = string.Format("{0}.{1}Access,{2}", "SelectedDatesExample", tn.Replace(" ", "_"), "SelectedDatesExample");
                return BaseClasses.Data.BaseTable.CreateInstance(tn);
            }
        }
    }
}