using System;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DebriefingSoftware.Common;
using DebriefingSoftware.Common.Business;
using Telerik.Web.UI;

namespace B4Restore.Common.Control
{
	public partial class DSGridView
	{
		public delegate void TDataForExport();
		public TDataForExport DataExport;
		private DSExportType? _currentlyExportingType;
		public string ShowProgressPanelString;
		public string HideProgressPanelString;

		private bool IsExport
		{
			get { return _currentlyExportingType.HasValue; }
		}

		protected void ExportToExcelClick(object sender, EventArgs e)
		{
			// to fix ssl and IE issue
			Page.Response.ClearHeaders();
			Page.Response.Cache.SetCacheability(HttpCacheability.Private);

			_currentlyExportingType = DSExportType.Excel;
			if (DataExport != null)
			{
				//Get data for the grid from the session
				DataExport.Invoke();
			}
			BorderStyle = BorderStyle.None;
			MasterTableView.BorderStyle = BorderStyle.None;
			MasterTableView.Style["border-collapse"] = "collapse";
			PageSize = MasterTableView.VirtualItemCount;
			MasterTableView.PageSize = MasterTableView.VirtualItemCount;
			CurrentPageIndex = 0;
			ExportSettings.OpenInNewWindow = true;
			ExportSettings.ExportOnlyData = true;
			ExportSettings.Excel.Format = GridExcelExportFormat.Html;
			HttpContext.Current.Response.Expires = 10;

			MasterTableView.UseAllDataFields = true;
			Rebind();
			MasterTableView.ExportToExcel();
			//currentlyExportingType = null;
		}

		protected void ExportToPdfClick(object sender, EventArgs e)
		{
			_currentlyExportingType = DSExportType.Pdf;
			if (DataExport != null)
			{
				DataExport.Invoke();
			}
			ExportSettings.OpenInNewWindow = true;
			BorderStyle = BorderStyle.None;
			MasterTableView.BorderStyle = BorderStyle.None;
			MasterTableView.Style["border-collapse"] = "collapse";

			MasterTableView.UseAllDataFields = false;
			MasterTableView.AllowSorting = false;
			Rebind();
			MasterTableView.ExportToPdf();
			//currentlyExportingType = null;
		}

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

			_loadingPanel = new RadAjaxLoadingPanel { Skin = "Vista", ID = "Panel" + ClientID };
			Controls.Add(_loadingPanel);

			if (IsExport)
			{
				foreach (GridColumn column in Columns)
				{
					bool noVisibleLabel = false;
					foreach (GridDataItem item in MasterTableView.Items)
					{
						foreach (System.Web.UI.Control ctrl in item[column].Controls)
						{
							if (ctrl is ITextControl && !String.IsNullOrEmpty((ctrl as ITextControl).Text.Trim()))
							{
								noVisibleLabel = true;
							}
						}
					}
					if (!noVisibleLabel)
					{
						column.Visible = false;
					}
				}
			}
			if (Enabled && !Page.IsPostBack)
			{
				var divPaging = _dsGridClientPager == null ? null : _dsGridClientPager.FindRecursive<System.Web.UI.Control>("divPaging");
				var spanpagingTotalDataCount = _dsGridClientPager == null ? null : _dsGridClientPager.FindRecursive<System.Web.UI.Control>("spanpagingTotalDataCount");
				var spanpagingTotalPages = _dsGridClientPager == null ? null : _dsGridClientPager.FindRecursive<System.Web.UI.Control>("spanpagingTotalPages");
				var rcbChangePageSize = _dsGridClientPager == null ? null : _dsGridClientPager.FindRecursive<System.Web.UI.Control>("rcbChangePageSize");

				ShowProgressPanelString = "$find('" + _loadingPanel.ClientID + "').show('" + ClientID + @"');";
				HideProgressPanelString = "$find('" + _loadingPanel.ClientID + "').hide('" + ClientID + @"');";

				//Every <Apply filter> button contains corresponding jsonString[<group name>] that contains current json-encoded list of objects
				var scriptKey = "jsGridVars" + UniqueID;
				var scriptBlock = new StringBuilder(@"var tableView = null; FirstLoad = true;");

				Page.ClientScript.RegisterClientScriptBlock(GetType(), scriptKey, scriptBlock.ToString(), true);

				scriptKey = "jsDSGrid" + UniqueID;

				scriptBlock.AppendLine(@"
				function DSGridView" + ClientID + @"_MasterTableViewCreated(sender, eventArgs) {" + ShowProgressPanelString + @"
					tableView = $find('" + ClientID + @"').get_masterTableView();
					$('#" + ClientID + @"').bind('owncommand', DSGridView" + ClientID + @"_OwnCommand);");
				scriptBlock.Append(@"
					tableView.set_currentPageIndex(0);
					Sys.Net.WebServiceProxy.invoke('" + HttpContext.Current.Response.ApplyAppPathModifier(string.Format("~/WebServices/{0}.svc", DataBindingService)) + @"','" + DataBindingMethod + @"', false, { 'startIndex' : tableView.get_currentPageIndex(), 'maximumRows' : tableView.get_pageSize(), 'sortExpressions' : tableView.get_sortExpressions().toString(), 'filterExpressions' : typeof jsonString == 'undefined' ? '' : jsonString['" + (FilterGroup == string.Empty ? "Unnamed" : FilterGroup) + @"'] }, DSGridView" + ClientID + @"_Succeeded, DSGridView" + ClientID + @"_Failed);
				}");

				scriptBlock.AppendLine(@"
				function DSGridView" + ClientID + @"_Succeeded(result, eventArgs) {
					tableView.set_dataSource(result.Data);
					tableView.RecordCount = result.Count;
					tableView.dataBind();
					// Sys.Debug.traceDump(tableView);
					// hide progress bar
					" + HideProgressPanelString +
					@"// rebuild paging
					generatePaging" + ClientID + @"(result.Count);
				}");

				scriptBlock.AppendLine(@"
				function RadGridDebriefitClientPager_PageIndex" + ClientID + @"(currentPageIndex) {
				tableView.set_currentPageIndex(currentPageIndex);
				DSGridView" + ClientID + @"_Paging(tableView.get_pageSize(), tableView.get_currentPageIndex());
				return false; }");

				scriptBlock.AppendLine(@"
				function generatePaging" + ClientID + @"(recordCount) {
					var rcbChangePageSize = " + (rcbChangePageSize == null ? "null" : "$find('" + rcbChangePageSize.ClientID + "')") + @";
					var divPaging = " + (divPaging == null ? "null" : "document.getElementById('" + divPaging.ClientID + "')") + @";
					var spanpagingTotalDataCount = " + (spanpagingTotalDataCount == null ? "null" : "document.getElementById('" + spanpagingTotalDataCount.ClientID + "')") + @";
					var spanpagingTotalPages = " + (spanpagingTotalPages == null ? "null" : "document.getElementById('" + spanpagingTotalPages.ClientID + "')") + @";
					var pageCount = Math.ceil(recordCount / tableView.get_pageSize());
					if (divPaging != null)
					{
						divPaging.innerHTML = '';
						for (i = 0; i < pageCount; i++)
						{
							var a = document.createElement('a'); 
							if (i == tableView.get_currentPageIndex()) {
								a.className = 'pseudoa bold';
							}
							a.setAttribute('onclick', 'RadGridDebriefitClientPager_PageIndex" + ClientID + @"(' + i + ')');
							a.innerHTML = i + 1;
							divPaging.appendChild(a);
						}
						spanpagingTotalDataCount.innerHTML = recordCount;
						spanpagingTotalPages.innerHTML = pageCount;
						if (rcbChangePageSize != null) {");

				scriptBlock.Append(@"

							var allRecordItem = rcbChangePageSize.findItemByText('All records');
							if (allRecordItem == null) {
								allRecordItem = new Telerik.Web.UI.RadComboBoxItem();
								allRecordItem.set_text('All records');
								allRecordItem.set_value(recordCount);
								rcbChangePageSize.trackChanges();
								rcbChangePageSize.get_items().add(allRecordItem);
								rcbChangePageSize.commitChanges();
							}
							else {
								rcbChangePageSize.trackChanges();
								allRecordItem.set_value(recordCount);
								rcbChangePageSize.commitChanges();
							}
						}
					}
				}");

				scriptBlock.AppendLine(@"
				function DSGridView" + ClientID + @"_Failed(error)
				{
					" + HideProgressPanelString + @"
				}");

				scriptBlock.AppendLine(@"
				function DSGridView" + ClientID + @"_Command(sender, eventArgs) {
					eventArgs.set_cancel(true);
					if (eventArgs.get_commandName() == 'Sort') {
						" + ShowProgressPanelString +
						@"tableView.set_currentPageIndex(0);
						Sys.Net.WebServiceProxy.invoke('" + HttpContext.Current.Response.ApplyAppPathModifier(string.Format("~/WebServices/{0}.svc", DataBindingService)) + @"','" + DataBindingMethod + @"', false, { 'startIndex' : tableView.get_currentPageIndex(), 'maximumRows' : tableView.get_pageSize(), 'sortExpressions' : tableView.get_sortExpressions().toString(), 'filterExpressions' : typeof jsonString == 'undefined' ? '' : jsonString['" + (FilterGroup == string.Empty ? "Unnamed" : FilterGroup) + @"'] }, DSGridView" + ClientID + @"_Succeeded, DSGridView" + ClientID + @"_Failed);
					}
				}");

				scriptBlock.AppendLine(@"
				//FilterExpressions is our packed json object list, encoded with js encode method
				function DSGridView" + ClientID + @"_OwnCommand(sender, eventArgs) {
				   " + ShowProgressPanelString + @"
					var startIndex = tableView.get_currentPageIndex() * tableView.get_pageSize();
					switch (eventArgs.CommandName) {																																				  
						case 'Filter':
							startIndex = 0;
							break;
						default:
							break;
					}
					Sys.Net.WebServiceProxy.invoke('" + HttpContext.Current.Response.ApplyAppPathModifier(string.Format("~/WebServices/{0}.svc", DataBindingService)) + @"','" + DataBindingMethod + @"', false, { 'startIndex' : startIndex, 'maximumRows' : tableView.get_pageSize(), 'sortExpressions' : tableView.get_sortExpressions().toString(), 'filterExpressions' : typeof jsonString == 'undefined' ? '' : jsonString['" + (FilterGroup == string.Empty ? "Unnamed" : FilterGroup) + @"'] }, DSGridView" + ClientID + @"_Succeeded, DSGridView" + ClientID + @"_Failed);
				}");

				scriptBlock.AppendLine(@"
				function DSGridView" + ClientID + @"_RowDataBound(sender, eventArgs) {
				}");

				scriptBlock.AppendLine(@"
				function DSGridView" + ClientID + @"_RowCreated(sender, eventArgs) {
				}");

				scriptBlock.AppendLine(@"
				function DSGridView" + ClientID + @"_Paging(pageSize, currentPageIndex) {
				   " + ShowProgressPanelString + @"
					var startIndex = currentPageIndex * pageSize;
					Sys.Net.WebServiceProxy.invoke('" + HttpContext.Current.Response.ApplyAppPathModifier(string.Format("~/WebServices/{0}.svc", DataBindingService)) + @"','" + DataBindingMethod + @"', false, { 'startIndex' : startIndex, 'maximumRows' : pageSize, 'sortExpressions' : tableView.get_sortExpressions().toString(), 'filterExpressions' : typeof jsonString == 'undefined' ? '' : jsonString['" + (FilterGroup == string.Empty ? "Unnamed" : FilterGroup) + @"'] }, DSGridView" + ClientID + @"_Succeeded, DSGridView" + ClientID + @"_Failed);
				}");

				scriptBlock.AppendLine(@"
				function DSGridView" + ClientID + @"_DataBinding(sender, eventArgs)
				{
					// This event will be raised twice by default!
					// The first call will retrieve data and the second call will retrieve total items count.
					// If you want to cancel the event you can use:
					// eventArgs.set_cancel(true);
		
					// get data source location, method name and arguments
					var dataSourceLocation = eventArgs.get_location();
					var selectMethodName = eventArgs.get_methodName();
					var methodArguments = eventArgs.get_methodArguments();
		   
					// set data source location and method name
					// eventArgs.set_location('url to your data source');
					// eventArgs.set_methodName('your method name');
		   
					// The grid will always pass by default four arguments for the SelectMethod.
					// SelectCountMethod will be called with no arguments by default!
		   
					// get names for select parameters
					// var startRowIndexParameterName = sender.ClientSettings.DataBinding.StartRowIndexParameterName;
					// default is 'startRowIndex'.
		   
					// var maximumRowsParameterName = sender.ClientSettings.DataBinding.MaximumRowsParameterName;
					// default is 'maximumRows'
		   
					// var sortParameterName = sender.ClientSettings.DataBinding.SortParameterName;
					// default is 'sortExpression'
		   
					// var filterParameterName = sender.ClientSettings.DataBinding.FilterParameterName;
					// default is 'filterExpression'
		   
					// construct your own arguments
					// var customArguments = new Object();
					// customArguments.someName = someValue;
					// eventArgs.set_methodArguments(customArguments);
				}");

				Page.ClientScript.RegisterClientScriptBlock(GetType(), scriptKey, scriptBlock.ToString(), true);
			}

			_currentlyExportingType = null;
		}
	}
}