using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DebriefingSoftware.Common;
using DebriefingSoftware.Common.Business.Filtering;

namespace B4Restore.Common.Control
{
	[ToolboxData("<{0}:FilterScriptHolder runat=server></{0}:FilterScriptHolder>")]
	public class FilterScriptHolder : PlaceHolder
	{
		private string _group;

		[PersistenceMode(PersistenceMode.Attribute)]
		public string Group { get { return _group; } set { _group = value.ToLower(); } }

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

			var scriptKey = "jsonString";
			var scriptBlock = new StringBuilder("var jsonString = []; var jsonStringInitial = [];");
			var sameGroupGrids = (from dsGridView in this.Page.GetControlListOnCreateNew<DSGridView>(typeof(DSGridView)) where dsGridView.FilterGroup == Group || dsGridView.FilterGroup == string.Empty select dsGridView);
			var urlFilterParameters = (from string urlParameterName in HttpContext.Current.Request.QueryString.Keys
									   where urlParameterName.StartsWith(Filter.FilterPrefix)
									   select Filter.GetFilterParameter(HttpContext.Current.Request.QueryString[urlParameterName])).Where(urlFilterParameter => urlFilterParameter.Group == Group || urlFilterParameter.Group == string.Empty).ToList();
			var filterHolders = this.Page.GetControlListOnCreateNew<FilterHolder>(typeof(FilterHolder));
			var newUrlFilterParameters = new List<FilterParameter>();

			FilterParameter filterParameter;

			foreach (var filterHolder in filterHolders)
			{
				filterParameter = filterHolder.GetFilterParameter();
				foreach (var urlFilterParameter in urlFilterParameters)
				{
					if (urlFilterParameter.FieldName == filterParameter.FieldName)
					{
						filterHolder.SetFilterValues(urlFilterParameter.FieldValues);
					}
					else
					{
						newUrlFilterParameters.Add(urlFilterParameter);
					}
				}
			}

			Filter.Current.ClearUrl();
			Filter.Current.AddUrlParameters(newUrlFilterParameters);

			var parameters = (from filterHolder in this.Page.GetControlListOnCreateNew<FilterHolder>(typeof(FilterHolder)) where filterHolder.Group == Group || filterHolder.Group == string.Empty select filterHolder.GetFilterParameter()).Union(newUrlFilterParameters);

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

			scriptKey = "jsFilterButtonHolder" + (Group == string.Empty ? "Unnamed" : Group);
			scriptBlock.AppendLine("jsonString['" + (Group == string.Empty ? "Unnamed" : Group) + @"'] = " + Filter.GetJsonString(parameters).EncodeJsString() + @";");
			scriptBlock.AppendLine("jsonStringInitial['" + (Group == string.Empty ? "Unnamed" : Group) + @"'] = jsonString['" + (Group == string.Empty ? "Unnamed" : Group) + @"'];");

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

			scriptKey = "jsGetFilterValues";
			scriptBlock.AppendLine(@"function jsGetFilterValues(filterParameter) {
					var fieldValues = [];
					switch (filterParameter.ControlType) {
						case " + (int)FilterControlType.RadTimePicker + @":
							var radTimePicker = $('#' + filterParameter.ControlClientID);
							if (radTimePicker == null) {
								break;
							}
							if (radTimePicker.get_selectedDate() != null)
							{
								fieldValues.push(dateFormat(radTimePicker.get_selectedDate(), 'yyyy-mm-dd-HH.MM.ss.000000'));
							}
							break;
						case " + (int)FilterControlType.RadDateTimePicker + @":
							var radDateTimePicker = $('#' + filterParameter.ControlClientID);
							if (radDateTimePicker == null) {
								break;
							}
							if (radDateTimePicker.get_selectedDate() != null)
							{
								fieldValues.push(dateFormat(radDateTimePicker.get_selectedDate(), 'yyyy-mm-dd-HH.MM.ss.000000'));
							}
							break;
						case " + (int)FilterControlType.RadDatePicker + @":
							var radDatePicker = $('#' + filterParameter.ControlClientID);
							if (radDatePicker == null) {
								break;
							}
							if (radDatePicker.get_selectedDate() != null)
							{
								fieldValues.push(dateFormat(radDatePicker.get_selectedDate(), 'yyyy-mm-dd-HH.MM.ss.000000'));
							}
							break;
						case " + (int)FilterControlType.ListBox + @":
							var listBox = $('#' + filterParameter.ControlClientID);
							Sys.Debug.traceDump('Schas vsyo budet...   ');
							Sys.Debug.traceDump($find('masterBody'));
							if (listBox == null) {
								break;
							}
							$('#' + filterParameter.ControlClientID + ' :selected').each(function(i, selected){ fieldValues.push($(selected).val()) });
							break;
						case " + (int)FilterControlType.DropDownList + @":
							var dropDownList = $('#' + filterParameter.ControlClientID);
							if (dropDownList == null) {
								break;
							}
							var dropDownListValue = $('#' + filterParameter.ControlClientID).val();
							if (dropDownListValue != '') {
								fieldValues.push(dropDownListValue);
							}
							break;
						case " + (int)FilterControlType.CheckBox + @":
							var checkBox = $('#' + filterParameter.ControlClientID);
							if (checkBox == null) {
								break;
							}
							fieldValues.push(checkBox.is(':checked') ? 1 : 0);
							break;
						case " + (int)FilterControlType.RadioButtonList + @":
							var radioButtonList = $('#' + filterParameter.ControlClientID);
							alert(radioButtonList);
							if (radioButtonList == null) {
								break;
							}
							Sys.Debug.traceDump(radioButtonList);
							var radioButtonValue = $('#' + filterParameter.ControlClientID + ':checked').val();
							alert(radioButtonList.html());
							if (radioButtonValue != '') {
								//fieldValues.push(radioButtonValue);
							}
							break;
						case " + (int)FilterControlType.TextBox + @":
							var textBox = $('#' + filterParameter.ControlClientID);
							if (textBox == null) {
								break;
							}
							var textBoxValue =  $('#' + filterParameter.ControlClientID).val();
							if (textBoxValue != '') {
								fieldValues.push(textBoxValue);
							}
							break;
					}
					return fieldValues;
				}");

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

			scriptKey = "jsClearFilterValues";
			scriptBlock.AppendLine(@"function jsClearFilterValues(filterParameter) {
					switch (filterParameter.ControlType) {
						case " + (int)FilterControlType.RadTimePicker + @":
							var radTimePicker = $('#' + filterParameter.ControlClientID);
							if (radTimePicker == null) {
								break;
							}
							radTimePicker.set_selectedDate(filterParameter.FieldValues[0]);
							break;
						case " + (int)FilterControlType.RadDateTimePicker + @":
							var radDateTimePicker = $('#' + filterParameter.ControlClientID);
							if (radDateTimePicker == null) {
								break;
							}
							radDateTimePicker.set_selectedDate(filterParameter.FieldValues[0]);
							break;
						case " + (int)FilterControlType.RadDatePicker + @":
							var radDatePicker = $('#' + filterParameter.ControlClientID);
							if (radDatePicker == null) {
								break;
							}
							radDatePicker.set_selectedDate(filterParameter.FieldValues[0]);
							break;
						case " + (int)FilterControlType.ListBox + @":
							var listBox = $('#' + filterParameter.ControlClientID);
							if (listBox == null) {
								break;
							}
							$('#' + filterParameter.ControlClientID + ' option').each(function(i, option){ $.inArray($(option).val(), filterParameter.FieldValues) == -1 ? $(option).removeAttr('selected') : $(option).attr('selected', 'selected'); });
							break;
						case " + (int)FilterControlType.DropDownList + @":
							var dropDownList = $('#' + filterParameter.ControlClientID);
							if (dropDownList == null) {
								break;
							}
							filterParameter.FieldValues.Length == 1 ? dropDownList.val(filterParameter.FieldValues[0]) : dropDownList.removeAttr('selected');
							break;
						case " + (int)FilterControlType.CheckBox + @":
							var checkBox = $('#' + filterParameter.ControlClientID);
							if (checkBox == null) {
								break;
							}
							checkBox.attr('checked', filterParameter.FieldValues[0] == '1');
							break;
						case " + (int)FilterControlType.RadioButtonList + @":
							var radioButtonList = $('#' + filterParameter.ControlClientID);
							if (radioButtonList == null) {
								break;
							}
							Sys.Debug.traceDump(radioButtonList);
							$('#' + filterParameter.ControlClientID).each(function(){ alert($(this)); $.inArray($(radio).val(), filterParameter.FieldValues) == -1 ? $(radio).removeAttr('checked') : $(radio).attr('checked', 'checked'); });
							break;
						case " + (int)FilterControlType.TextBox + @":
							var textBox = $('#' + filterParameter.ControlClientID);
							if (textBox == null) {
								break;
							}
							var textBox =  $('#' + filterParameter.ControlClientID);
							textBox.val(filterParameter.FieldValues[0]);
							break;
					}
					return;
				}");


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

			if (Controls.Count > 0)
			{
				var sameGroupGridFireCommandString = string.Empty;
				var applyButtonControl = Controls.OfType<ApplyButton>();
				if (applyButtonControl.Count() == 1)
				{
					var applyButton = applyButtonControl.First();

					scriptKey = "jsApplyFilterAction" + (Group == string.Empty ? "Unnamed" : Group);
					scriptBlock.AppendLine(@"function jsApplyFilterAction" + (Group == string.Empty ? "Unnamed" : Group) +
										   @"() {
					var jsonStringTmp = '';
					for (var parameterKey in filterParameters) {
						if (jsonStringTmp != '') {
							jsonStringTmp += ',';
						}
						if (filterParameters[parameterKey].Group == '" + Group + @"' || filterParameters[parameterKey].Group == '') {
							filterParameters[parameterKey].FieldValues = jsGetFilterValues(filterParameters[parameterKey]);
							jsonStringTmp += JSON.stringify(filterParameters[parameterKey]);
						}
					}
					jsonString['" + (Group == string.Empty ? "Unnamed" : Group) + @"'] = encodeURIComponent('[' + jsonStringTmp + ']');");
					sameGroupGridFireCommandString = sameGroupGrids.Aggregate(sameGroupGridFireCommandString,
																			  (current, grid) =>
																			  current +
																			  (@"$('#" + grid.ClientID +
																			   @"').trigger('owncommand', { CommandName : 'Filter', FilterExpressions : jsonString['" +
																			   (Group == string.Empty ? "Unnamed" : Group) + @"'] });"));
					scriptBlock.AppendLine(sameGroupGridFireCommandString);
					scriptBlock.AppendLine(@"return false; }");

					Page.ClientScript.RegisterClientScriptBlock(GetType(), scriptKey, scriptBlock.ToString(), true);
					applyButton.OnClientClick = "return jsApplyFilterAction" + (Group == string.Empty ? "Unnamed" : Group) + @"()";
				}
				var clearButtonControl = Controls.OfType<ClearButton>();
				if (clearButtonControl.Count() == 1)
				{
					var clearButton = clearButtonControl.First();

					scriptKey = "jsClearFilterAction" + (Group == string.Empty ? "Unnamed" : Group);
					scriptBlock.AppendLine(@"function jsClearFilterAction" + (Group == string.Empty ? "Unnamed" : Group) +
										   @"() {
					var initialFilterParameters = JSON.parse(jsonStringInitial['" + (Group == string.Empty ? "Unnamed" : Group) + @"']);
					for (var parameterKey in initialFilterParameters) {
						if (initialFilterParameters[parameterKey].Group == '" + Group + @"' || initialFilterParameters[parameterKey].Group == '') {
							jsClearFilterValues(initialFilterParameters[parameterKey]);
						}
					}
					jsonString['" + (Group == string.Empty ? "Unnamed" : Group) + @"'] = jsonStringInitial['" + (Group == string.Empty ? "Unnamed" : Group) + @"'];");
					sameGroupGridFireCommandString = sameGroupGrids.Aggregate(sameGroupGridFireCommandString,
																			  (current, grid) =>
																			  current +
																			  (@"$('#" + grid.ClientID +
																			   @"').trigger('owncommand', { CommandName : 'Filter', FilterExpressions : jsonString['" +
																			   (Group == string.Empty ? "Unnamed" : Group) + @"'] });"));
					scriptBlock.AppendLine(sameGroupGridFireCommandString);
					scriptBlock.AppendLine(@"return false; }");

					Page.ClientScript.RegisterClientScriptBlock(GetType(), scriptKey, scriptBlock.ToString(), true);
					clearButton.OnClientClick = "return jsClearFilterAction" + (Group == string.Empty ? "Unnamed" : Group) + @"()";
				}
			}
		}
	}
}
