using C1.Web.Wijmo.Controls.C1GridView;
using System;
using System.Data;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace GridView_RowsSample
{
    // Stands in for your BaseUserControl. The key detail being reproduced:
    // this control calls ShowMessageDialog() from its own OnInit, and it sits
    // EARLIER in the control tree (inside the ContentPlaceHolder) than
    // MessageDialog1 (a direct child of the Master's <form>, declared later
    // in Site.Master's markup).
    //
    // ASP.NET's InitRecursive does a post-order traversal: a control's children
    // finish InitRecursive (and therefore OnInit) before the control itself,
    // and siblings are processed in declaration order. Because FaultyControl's
    // whole branch (ContentPlaceHolder -> Content -> FaultyControl) is declared
    // before MessageDialog1 in the form, FaultyControl.OnInit fires BEFORE
    // C1Window1.OnInit ever runs — so C1Window1.EnsureChildControls() hasn't
    // happened yet, and lblMessage is still null.
    public partial class FaultyControl : UserControl
    {
		public string CurrencySymbolHtml => System.Globalization.CultureInfo.CurrentCulture.NumberFormat.CurrencySymbol;

			static Exception _exception;

		object _dataSource;
		public object DataSource
		{
			get { return _dataSource; }
			set { _dataSource = value; }
		}


		protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            try
            {
                ///////throw new InvalidOperationException("(MY CUSTOM DIALOG) Something went wrong while initializing this control.");
            }
            catch(Exception ex)
            {
                _exception = ex;
            }
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            
            if(_exception != null)
            {
                System.Diagnostics.Debug.WriteLine(_exception);

                //var master = (SiteMaster)Page.Master;
                //master.ShowMessageDialog(new MessageDialogOptions
                //{
                //    Title = "Error",
                //    Message = _exception.Message,
                //    Icon = DialogIcon.Error,
                //    DialogButtons = DialogButtons.OkOnly
                //});
            }
        }
		protected void Page_Load(object sender, EventArgs e)
		{
			if (!IsPostBack)
			{
				//LoadEmptyData();
				UpdatePanel1.Update();

				//BindGrid(null);

				string initScript = @"
                    Sys.Application.add_load(function () {
                        console.log('Sys.Application.add_load fired (registered on initial load only)');
                        ReadRows();
                    });";
				//ClientScript.RegisterStartupScript(
				//	GetType(), "readRowsInit", initScript, true);
			}
		}

		protected void ClearGridValues()
		{
			foreach (C1GridViewRow row in C1GridView1.Rows)
			{
				//var hidden = (HiddenField)row.FindControl("HiddenAmount");
				//if (hidden != null)
				//{
				//	hidden.Value = "0";
				//}
			}
			UpdatePanel1.Update();
		}


		public override void DataBind()
		{
			ClearGridValues();
			var dt = (DataTable)_dataSource;
			C1GridView1.DataSource = dt;
			C1GridView1.DataBind();
			UpdatePanel1.Update();

			// GroupInfo on the hidden column — all rows share the same CATEGORY value
			// so they form one group, producing a single Total footer row
			if (C1GridView1.Columns.Count > 0)
			{
				var col = (C1BoundField)C1GridView1.Columns[0];
				col.GroupInfo.GroupSingleRow = false;
				col.GroupInfo.Position = GroupPosition.Footer;
				col.GroupInfo.FooterText = "Total:";
				col.GroupInfo.OutlineMode = OutlineMode.StartExpanded;
				col.RowMerge = RowMerge.Free;
			}
		}


		private static DataTable GetData()
		{
			var dt = new DataTable();
			dt.Columns.Add("Id");
			dt.Columns.Add("Name");
			dt.Columns.Add("Desc");
			dt.Columns.Add("Check", typeof(bool));

			// 50 rows to simulate a heavier grid like 
			for (int i = 1; i <= 50; i++)
			{
				dt.Rows.Add(i, "name-" + i, "desc-" + i, i % 2 == 0);
			}
			return dt;
		}

		private void BindGrid(string nameFilter)
		{
			var dt = GetData();
			if (nameFilter != null)
			{
				var filtered = dt.AsEnumerable()
					.Where(r => r["Name"].ToString().ToLower().Contains(nameFilter));
				dt = filtered.Any() ? filtered.CopyToDataTable() : dt.Clone();
			}
			C1GridView1.DataSource = dt;
			C1GridView1.DataBind();
		}
		protected void C1GridView1_RowDataBound(object sender,
		  C1.Web.Wijmo.Controls.C1GridView.C1GridViewRowEventArgs e)
		{
			if (e.Row.RowType == C1.Web.Wijmo.Controls.C1GridView.C1GridViewRowType.DataRow)
			{
				var rowData = (DataRowView)e.Row.DataItem;

				//var tripJson = "{\"id\":" + rowData["Id"] +
				//	",\"name\":\"" + rowData["Name"] + "\"}";
				//e.Row.Attributes["trip"] = tripJson;

				// Simulate heavier server-side rendering like  complex grid
				System.Threading.Thread.Sleep(50);
			}
		}

	}
}
