using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection;
using DebriefingSoftware.Common.Business;
using DebriefingSoftware.Web.PresentationObjects;
using Telerik.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI;
using System.ComponentModel;
using DebriefingSoftware.Common;

namespace B4Restore.Common.Control
{
	internal interface IExportFormats
	{
		[DefaultValueAttribute("")]
		[PersistenceMode(PersistenceMode.Attribute)]
		string ExportFormats { get; set; }

		List<DSExportType> ExportTypes { get; }
	}

	[ToolboxData("<{0}:HeaderBar runat=server></{0}:HeaderBar>")]
	public class HeaderBar : Panel { }

	[ToolboxData("<{0}:FilterBar runat=server></{0}:FilterBar>")]
	public class FilterBar : Panel { }

	[ToolboxData("<{0}:DSGridView runat=server></{0}:DSGridView>")]
	public partial class DSGridView : RadGrid
	{
		public class HeaderSection : Panel { }
		public class ButtonSection : Panel { }

		public RadAjaxLoadingPanel _loadingPanel;

		/// <summary>
		/// Name of WCF service method
		/// </summary>
		[DefaultValueAttribute("")]
		[PersistenceMode(PersistenceMode.Attribute)]
		public string DataBindingMethod
		{
			get;
			set;
		}

		/// <summary>
		/// Name of WCF service
		/// </summary>
		[DefaultValueAttribute("")]
		[PersistenceMode(PersistenceMode.Attribute)]
		public string DataBindingService
		{
			get;
			set;
		}

		private string _filterGroup;

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

		private DSGridClientPager _dsGridClientPager;
		private TextBox _dsPageSize;
  
		public sealed class ExportToExcelButton : LinkButton
		{
			private readonly System.Web.UI.WebControls.Image _image = new System.Web.UI.WebControls.Image();
			public ExportToExcelButton(string commandArgument, EventHandler click, string ID, string cssClass, string text, string toolTip, string imageUrl, DSExportType exportType)
			{
				_image.ImageUrl = imageUrl;
				this.CommandArgument = commandArgument;
				this.Click += click;
				this.ID = ID;
				this.CssClass = cssClass;
				this.Text = text;
				this.ToolTip = toolTip;
				CommandName = exportType.ToString();
			}

			protected override void CreateChildControls()
			{
				if (!Visible)
				{
					return;
				}
				Controls.Clear();

				var div = new Panel { CssClass = "floatRight paddingLeft4px paddingRight4px paddingTop4px paddingBottom4px" };
				div.Controls.Add(_image);
				Controls.Add(div);
			}
		}
		private ExportToExcelButton _exportToExcelButton;

		public sealed class ExportToPdfButton : LinkButton
		{
			private readonly System.Web.UI.WebControls.Image _image = new System.Web.UI.WebControls.Image();
			public ExportToPdfButton(string commandArgument, EventHandler click, string ID, string cssClass, string text, string toolTip, string imageUrl, DSExportType exportType)
			{
				_image.ImageUrl = imageUrl;
				this.CommandArgument = commandArgument;
				this.Click += click;
				this.ID = ID;
				this.CssClass = cssClass;
				this.Text = text;
				this.ToolTip = toolTip;
				CommandName = exportType.ToString();
			}

			protected override void CreateChildControls()
			{
				Controls.Clear();
				var div = new Panel { CssClass = "floatRight paddingLeft4px paddingRight4px paddingTop4px paddingBottom4px" };
				div.Controls.Add(_image);
				Controls.Add(div);
			}
		}
		private ExportToPdfButton _exportToPdfButton;

		[DefaultValueAttribute("")]
		[PersistenceMode(PersistenceMode.Attribute)]
		public string MasterTableViewCaption
		{
			get;
			set;
		}

		[DefaultValueAttribute("")]
		[PersistenceMode(PersistenceMode.Attribute)]
		public string MasterTableViewCssClass
		{
			get;
			set;
		}

		[DefaultValueAttribute("")]
		[PersistenceMode(PersistenceMode.Attribute)]
		public string ExportEnabledFormats
		{
			get;
			set;
		}

		public List<DSExportType> ExportEnabledTypes
		{
			get
			{
				return ExportEnabledFormats.GetTypesFromSeparatedString<DSExportType>();
			}
		}

		protected override void OnInit(EventArgs e)
		{
			ImagesPath = "~/App_Themes/" + Page.Theme + "/DSGridView";
			EnableViewState = true;
			MasterTableView.EnableViewState = false;
			PagerStyle.AlwaysVisible = true;
			ClientSettings.ClientEvents.OnCommand = "DSGridView" + ClientID + "_Command";
			ClientSettings.ClientEvents.OnRowCreated = "DSGridView" + ClientID + "_RowCreated";
			ClientSettings.ClientEvents.OnDataBinding = "DSGridView" + ClientID + "_DataBinding";
			//ClientSettings.ClientEvents.OnRowDataBound = "DSGridView" + ClientID + "_RowDataBound";
			ClientSettings.ClientEvents.OnMasterTableViewCreated = "DSGridView" + ClientID + "_MasterTableViewCreated";
		}

		protected override void OnItemEvent(GridItemEventArgs e)
		{
			if (e.EventInfo is GridInitializePagerItem && e.Item is GridPagerItem)
			{
				e.Canceled = true;
				_dsGridClientPager = new DSGridClientPager((e.EventInfo as GridInitializePagerItem).PagingManager, e.Item.OwnerTableView, Page, PageSize);
				_dsPageSize = new TextBox { Text = "120", ReadOnly = true, CssClass = "SmallTextBox" };
				(e.Item as GridPagerItem).PagerContentCell.Controls.Add(_dsGridClientPager);
				(e.Item as GridPagerItem).PagerContentCell.Controls.Add(new Label { Text = "Initial Page Size&nbsp;" });
				(e.Item as GridPagerItem).PagerContentCell.Controls.Add(_dsPageSize);

				if (Parser.ParseNullableInt(_dsPageSize.Text).HasValue)
				{
					if (Parser.ParseNullableInt(_dsPageSize.Text).Value > 0)
					{
						PageSize = Parser.ParseNullableInt(_dsPageSize.Text).Value;
						MasterTableView.PageSize = Parser.ParseNullableInt(_dsPageSize.Text).Value;
					}
				}
			}
		}

		protected override void OnItemCreated(GridItemEventArgs e)
		{
			if (e.Item is GridCommandItem)
			{
				var item = e.Item as GridCommandItem;
				var headerBar_ = item.Controls[0].Controls.OfType<HeaderBar>().First();
				if (headerBar_ != null)
				{
					var buttonSection = new ButtonSection { CssClass = string.Format("floatRight") };
					if (ExportEnabledTypes.Contains(DSExportType.Excel))
					{
						_exportToExcelButton = new ExportToExcelButton(ID, ExportToExcelClick, string.Format("{0}_ExportToExcelButton", ID), "excelbutton", string.Empty, "Export this view to Excel", string.Format("{0}/{1}", ImagesPath, "excel.png"), DSExportType.Excel);
						buttonSection.Controls.Add(_exportToExcelButton);
					}
					if (ExportEnabledTypes.Contains(DSExportType.Pdf))
					{
						_exportToPdfButton = new ExportToPdfButton(ID, ExportToPdfClick, string.Format("{0}_ExportToPdfButton", ID), "pdfbutton", string.Empty, "Export this view to PDF", string.Format("{0}/{1}", ImagesPath, "pdf.png"), DSExportType.Pdf);
						buttonSection.Controls.Add(_exportToPdfButton);
					}
					headerBar_.Controls.Add(buttonSection);
					if (!string.IsNullOrEmpty(MasterTableViewCaption))
					{
						var headerSection = new HeaderSection { CssClass = string.Format("floatLeft") };
						var caption = new Panel { CssClass = string.Format("floatLeft paddingLeft4px paddingRight4px paddingTop4px paddingBottom4px {0}", MasterTableViewCssClass) };
						caption.Controls.Add(new Literal { Text = MasterTableViewCaption });
						headerSection.Controls.Add(caption);
						headerBar_.Controls.Add(headerSection);
					}
				}
				// IsExport is true when we click Export buttons (Excel, PDF, ...)
				if (IsExport)
				{
					item.Font.Name = "Verdana";
					item.Font.Bold = true;
					item.ForeColor = Color.Black;
				}
				// We hide export buttons for generated PDF, Excel, etc
				foreach (TableCell cell in item.Controls)
				{
					(from headerBar in cell.Controls.OfType<HeaderBar>() select headerBar).ToList().ForEach(
						headerBar => (from buttonSection in headerBar.Controls.OfType<ButtonSection>() select buttonSection).ToList().ForEach(buttonSection => buttonSection.Visible = !IsExport));
				}
			}
			if (e.Item is GridHeaderItem)
			{
				if (IsExport)
				{
					var item = e.Item as GridHeaderItem;
					item.Font.Name = "Verdana";
					item.Style["background-color"] = "#B5B5B5";
					item.Style["color"] = "#000000";
					foreach (TableCell cell in item.Cells)
					{
						cell.Style["padding"] = "2px";
						cell.Style["border"] = "1px solid #000000";
						if (cell.CssClass.Contains("ca"))
						{
							cell.Style["text-align"] = "center";	
						}
						else if (cell.CssClass.Contains("ra"))
						{
							cell.Style["text-align"] = "right";
						}
						else
						{
							cell.Style["text-align"] = "left";
						}
						cell.Style["text-transform"] = "uppercase";
					}
				}
			}
			if (e.Item is GridDataItem)
			{
				var item = e.Item as GridDataItem;
				if (IsExport)
				{
					item.Style.Clear();
					item.Font.Name = "Verdana";
					item.Style["background-color"] = (item.ItemType == GridItemType.AlternatingItem ? "#F3F3F3" : "#E2E2E2");
					item.Style["color"] = "#000000";
					foreach (TableCell cell in item.Cells)
					{
						cell.Style["padding"] = "2px";
						cell.Style["border"] = "1px solid #000000";
						if (cell.CssClass.Contains("ca"))
						{
							cell.Style["text-align"] = "center";
						}
						else if (cell.CssClass.Contains("ra"))
						{
							cell.Style["text-align"] = "right";
						}
						else
						{
							cell.Style["text-align"] = "left";
						}
					}
				}
				else
				{
					//to avoid bug when on initial load empty rows are shown in grid
					e.Item.Display = false;
				}
			}
		}

		protected override void OnItemDataBound(GridItemEventArgs e)
		{
			if (!IsExport)
			{
				return;
			}
			if (e.Item is GridDataItem)
			{
				var item = e.Item as GridDataItem;
				if (item.DataItem == null || item.DataItem is DataRowView)
				{
					return;
				}
				// if our data fields in the grid have Export attribute (see GridEntity.cs) - check if they should be shown (export type of the field contains currently exporting type)
				foreach (TableCell cell in item.Cells)
				{
					var labels = cell.Controls.OfType<WebControl>().OfType<Label>();
					foreach (var label in labels)
					{
						var property = item.DataItem.GetType().GetProperty(label.ID);
						if (property != null)
						{
							var exportAttribute = ((MemberInfo)property).GetCustomAttributes(true).Where(attributeInstance => attributeInstance is ExportAttribute).FirstOrDefault();
							if (exportAttribute != null && !((ExportAttribute)exportAttribute).ExportTypes.Contains(_currentlyExportingType.Value))
							{
								label.Visible = false;
							}
							if (label.Visible)
							{
								label.Text = DataBinder.Eval(item.DataItem, label.ID).ToString();
							}
						}
					}
				}
			}
		}
	}
}
