using System.Linq;
using System.Web;
using Telerik.Web.UI;
using System;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI;

namespace B4Restore.Common.Control
{
	internal sealed class DSGridClientPager : System.Web.UI.Control
	{
		private readonly GridPagingManager paging;
		private readonly GridTableView tableView;
		private readonly Page page;
		private readonly string theme;
		private readonly int gridPageCountPerPage;

		public DSGridClientPager(GridPagingManager paging, GridTableView tableView, Page page, int gridPageCountPerPage)
		{
			this.paging = paging;
			this.tableView = tableView;
			this.page = page;
			this.theme = page.Theme;
			this.gridPageCountPerPage = gridPageCountPerPage;
			EnsureChildControls();
		}

		protected override void OnPreRender(EventArgs e)
		{
			base.OnPreRender(e);
			var dsGridView = tableView.OwnerGrid as DSGridView;
			if (dsGridView == null)
			{
				return;
			}

			var scriptKey = "jsApplyPagerMethods" + UniqueID;

			var scriptBlock =
				"\n" + @"function RadGridDebriefitClientPager_SelectedIndexChanged" + dsGridView.ClientID + @"(sender, eventArgs) {" +
				@"tableView.set_pageSize(eventArgs.get_item().get_value());" +
				@"tableView.set_virtualItemCount(tableView.RecordCount);" +
				@"tableView.set_currentPageIndex(0);" +
				@"alert('Page count is ' + tableView.get_pageCount() + ', current page index is ' + tableView.get_currentPageIndex() + ', page size is ' + tableView.get_pageSize() + ', virtual item count is ' + tableView.get_virtualItemCount());" +
				@"DSGridView" + dsGridView.ClientID + @"_Paging(eventArgs.get_item().get_value(), tableView.get_currentPageIndex());" +
				@"return; }" +

				"\n" + @"function RadGridDebriefitClientPager_PageIndexFirst" + dsGridView.ClientID + @"() {" +
				@"tableView.set_currentPageIndex(0);" +
				@"DSGridView" + dsGridView.ClientID + @"_Paging(tableView.get_pageSize(), tableView.get_currentPageIndex());" +
				@"return false; }" +

				"\n" + @"function RadGridDebriefitClientPager_PageIndexPrev" + dsGridView.ClientID + @"() {" +
				@"if (tableView.get_currentPageIndex() > 0) { tableView.set_currentPageIndex(tableView.get_currentPageIndex() - 1); }" +
				@"DSGridView" + dsGridView.ClientID + @"_Paging(tableView.get_pageSize(), tableView.get_currentPageIndex());" +
				@"return false; }" +

				"\n" + @"function RadGridDebriefitClientPager_PageIndexNext" + dsGridView.ClientID + @"() {" +
				@"if (tableView.get_currentPageIndex()  < tableView.get_pageCount() - 1 && tableView.get_pageCount() > 1) { tableView.set_currentPageIndex(tableView.get_currentPageIndex() + 1); }" +
				@"DSGridView" + dsGridView.ClientID + @"_Paging(tableView.get_pageSize(), tableView.get_currentPageIndex());" +
				@"return false; }" +

				"\n" + @"function RadGridDebriefitClientPager_PageIndexLast" + dsGridView.ClientID + @"() {" +
				@"if (tableView.get_pageCount() > 0) { tableView.set_currentPageIndex(tableView.get_pageCount() - 1); }" +
				@"DSGridView" + dsGridView.ClientID + @"_Paging(tableView.get_pageSize(), tableView.get_currentPageIndex());" +
				@"return false; }";

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

		protected override void CreateChildControls()
		{
			var dsGridView = tableView.OwnerGrid as DSGridView;
			if (dsGridView == null)
			{
				return;
			}
			var pathToImages = "~/App_Themes/" + page.Theme + "/Grid";
			var pagingFirstImage = new Image { ImageUrl = String.Format("{0}/PagingFirst.gif", pathToImages), ToolTip = "First page" };
			var pagingPrevImage = new Image { ImageUrl = String.Format("{0}/PagingPrev.gif", pathToImages), ToolTip = "Previous page", CssClass = "marginRight8px" };
			var pagingNextImage = new Image { ImageUrl = String.Format("{0}/PagingNext.gif", pathToImages), ToolTip = "Next page", CssClass = "marginLeft8px" };
			var pagingLastImage = new Image { ImageUrl = String.Format("{0}/PagingLast.gif", pathToImages), ToolTip = "Last page" };
			var pagerTable = new HtmlTable
			{
				CellSpacing = 0,
				CellPadding = 2
			};
			pagerTable.Attributes.Add("class", "marginBottom4px marginLeft4px");
			var pagerTableRow = new HtmlTableRow();
			var pagerTableRowCellFirst = new HtmlTableCell();
			var pagerTableRowCellPrev = new HtmlTableCell();
			var pagerTableRowCellNext = new HtmlTableCell();
			var pagerTableRowCellLast = new HtmlTableCell();

			HtmlTableCell cell;

			var pagingFirstButton = new LinkButton { ID = "lbPagingFirst" };
			pagingFirstButton.Controls.Add(pagingFirstImage);
			pagingFirstButton.OnClientClick = String.Format("return RadGridDebriefitClientPager_PageIndexFirst{0}()",
															dsGridView.ClientID);
			pagerTableRowCellFirst.Controls.Add(pagingFirstButton);
			var pagingPrevButton = new LinkButton { ID = "lbPagingPrev" };
			pagingPrevButton.Controls.Add(pagingPrevImage);
			pagingPrevButton.OnClientClick = String.Format("return RadGridDebriefitClientPager_PageIndexPrev{0}()",
															dsGridView.ClientID);
			pagerTableRowCellPrev.Controls.Add(pagingPrevButton);

			pagerTableRow.Cells.Add(pagerTableRowCellFirst);
			pagerTableRow.Cells.Add(pagerTableRowCellPrev);

			cell = new HtmlTableCell();
			cell.Controls.Add(new HtmlGenericControl("div") { ID = "divPaging" });
			pagerTableRow.Cells.Add(cell);

			var pagingNextButton = new LinkButton { ID = "lbPagingNext" };
			pagingNextButton.Controls.Add(pagingNextImage);
			pagingNextButton.OnClientClick = String.Format("return RadGridDebriefitClientPager_PageIndexNext{0}()",
															dsGridView.ClientID);
			pagerTableRowCellNext.Controls.Add(pagingNextButton);
			var pagingLastButton = new LinkButton { ID = "lbPagingLast" };
			pagingLastButton.Controls.Add(pagingLastImage);
			pagingLastButton.OnClientClick = String.Format("return RadGridDebriefitClientPager_PageIndexLast{0}()",
															dsGridView.ClientID);
			pagerTableRowCellLast.Controls.Add(pagingLastButton);

			pagerTableRow.Cells.Add(pagerTableRowCellNext);
			pagerTableRow.Cells.Add(pagerTableRowCellLast);
			cell = new HtmlTableCell();
			cell.Attributes.Add("class", "spacer8px");
			pagerTableRow.Cells.Add(cell);

			cell = new HtmlTableCell();
			var radComboBox = new RadComboBox
			{
				EnableEmbeddedSkins = false,
				EnableTheming = true,
				Skin = theme,
				ID = "rcbChangePageSize",
				AutoPostBack = false,
				OnClientSelectedIndexChanged = "RadGridDebriefitClientPager_SelectedIndexChanged" + dsGridView.ClientID
			};

			var recordCountPerPage = new[] { 1, 2, 3, 4 };

			foreach (var i in recordCountPerPage)
			{
				if (paging.DataSourceCount < i)
				{
					break;
				}
				radComboBox.Items.Add(new RadComboBoxItem
				                      	{
				                      		Text = String.Format("{0}", i),
				                      		Value = String.Format("{0}", i)
				                      	});
			}

			if (gridPageCountPerPage > 0)
			{
				int comboBoxItem_Index = 0;
				var comboBoxItem =
					(from radComboBoxItem in radComboBox.Items
					 where int.Parse(radComboBoxItem.Value) > gridPageCountPerPage
					 select radComboBoxItem).FirstOrDefault();

				if (comboBoxItem == null)
				{
					var nearestLargerPageSizeItem = (from item in radComboBox.Items
					                                 where item.Value.CompareTo(gridPageCountPerPage.ToString()) > 0
					                                 select item).FirstOrDefault();
					if (nearestLargerPageSizeItem == null)
					{
						comboBoxItem_Index = radComboBox.Items.Count;
					}
					else
					{
						if (!int.TryParse(nearestLargerPageSizeItem.Value, out comboBoxItem_Index))
						{
							comboBoxItem_Index = radComboBox.Items.Count;
						}
					}
				}
				var customPageSizePosition = comboBoxItem == null ? comboBoxItem_Index : comboBoxItem.Index;
				var customPageSizeItem = radComboBox.Items.FindItemByValue(gridPageCountPerPage.ToString());

				if (customPageSizeItem == null)
				{
					radComboBox.Items.Insert(customPageSizePosition, new RadComboBoxItem
						                                                {
						                                                 	Text = String.Format("{0} (user setting)", gridPageCountPerPage),
						                                                 	Value = String.Format("{0}", gridPageCountPerPage)
						                                                });
				}
				else
				{
					customPageSizeItem.Text = String.Format("{0} (user setting)", gridPageCountPerPage);
				}
			}
			if (radComboBox.Items.FindItemByValue(paging.DataSourceCount.ToString()) == null)
			{
				radComboBox.Items.Add(new RadComboBoxItem
				{
					Text = String.Format("All records"),
					Value = String.Format("{0}", paging.DataSourceCount)
				});
			}
			var currentPageSizeItem = radComboBox.Items.FindItemByValue(gridPageCountPerPage.ToString());
			if (currentPageSizeItem != null)
			{
				currentPageSizeItem.Selected = true;
			}
			cell.Controls.Add(radComboBox);
			pagerTableRow.Cells.Add(cell);

			cell = new HtmlTableCell();
			var pageCountInfoBox = new Panel { CssClass = "marginLeft8px" };
			pageCountInfoBox.Controls.Add(new Label { ID = "spanpagingTotalDataCount", CssClass = "bold", Text = "0" });
			pageCountInfoBox.Controls.Add(new Literal { Text = "&nbsp;records in&nbsp;" });
			pageCountInfoBox.Controls.Add(new Label { ID = "spanpagingTotalPages", CssClass = "bold", Text = "1" });
			pageCountInfoBox.Controls.Add(new Literal { Text = "&nbsp;page(s)" });

			cell.Controls.Add(pageCountInfoBox);
			pagerTableRow.Cells.Add(cell);

			cell = new HtmlTableCell();
			pagerTableRow.Cells.Add(cell);

			////last cell
			//var lastControl = AddControlsToLastCellInPager();
			//if (lastControl != null)
			//{
			//    cell = new HtmlTableCell();
			//    cell.Controls.Add(lastControl);
			//    pagerTableRow.Cells.Add(cell);
			//}


			pagerTable.Rows.Add(pagerTableRow);
			Controls.Add(pagerTable);
		}
	}
}