using System;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using Northwind45.BusinessObject;
 
namespace Northwind45
{
    public partial class GridViewSearch_Products : System.Web.UI.Page
    {
        private string _validationErrors = String.Empty;
 
        protected void Page_Load(object sender, EventArgs e)
        {
            string parameter = Request["__EVENTARGUMENT"];
 
            SetSortImage(parameter);
            SetPaging(parameter);
        }
 
        private void SetSortImage(string parameter)
        {
            if (!String.IsNullOrEmpty(parameter) && parameter.Contains("Sort$"))
            {
                LitSortExpression.Text = parameter.Replace("Sort$""");
                LitSortDirection.Text = String.Empty;
 
                if (parameter == "Sort$ProductID")
                {
                    if (ImgSortProductID.ImageUrl.Contains("ArrowUp.png"))
                    {
                        ImgSortProductID.ImageUrl = "~/Images/ArrowDown.png";
                        LitSortDirection.Text = "desc";
                    }
                    else
                    {
                        ImgSortProductID.ImageUrl = "~/Images/ArrowUp.png";
                    }
                }
                else if (parameter == "Sort$ProductName")
                {
                    if (ImgSortProductName.ImageUrl.Contains("ArrowUp.png"))
                    {
                        ImgSortProductName.ImageUrl = "~/Images/ArrowDown.png";
                        LitSortDirection.Text = "desc";
                    }
                    else
                    {
                        ImgSortProductName.ImageUrl = "~/Images/ArrowUp.png";
                    }
                }
                else if (parameter == "Sort$SupplierID")
                {
                    if (ImgSortSupplierID.ImageUrl.Contains("ArrowUp.png"))
                    {
                        ImgSortSupplierID.ImageUrl = "~/Images/ArrowDown.png";
                        LitSortDirection.Text = "desc";
                    }
                    else
                    {
                        ImgSortSupplierID.ImageUrl = "~/Images/ArrowUp.png";
                    }
                }
                else if (parameter == "Sort$CategoryID")
                {
                    if (ImgSortCategoryID.ImageUrl.Contains("ArrowUp.png"))
                    {
                        ImgSortCategoryID.ImageUrl = "~/Images/ArrowDown.png";
                        LitSortDirection.Text = "desc";
                    }
                    else
                    {
                        ImgSortCategoryID.ImageUrl = "~/Images/ArrowUp.png";
                    }
                }
                else if (parameter == "Sort$QuantityPerUnit")
                {
                    if (ImgSortQuantityPerUnit.ImageUrl.Contains("ArrowUp.png"))
                    {
                        ImgSortQuantityPerUnit.ImageUrl = "~/Images/ArrowDown.png";
                        LitSortDirection.Text = "desc";
                    }
                    else
                    {
                        ImgSortQuantityPerUnit.ImageUrl = "~/Images/ArrowUp.png";
                    }
                }
                else if (parameter == "Sort$UnitPrice")
                {
                    if (ImgSortUnitPrice.ImageUrl.Contains("ArrowUp.png"))
                    {
                        ImgSortUnitPrice.ImageUrl = "~/Images/ArrowDown.png";
                        LitSortDirection.Text = "desc";
                    }
                    else
                    {
                        ImgSortUnitPrice.ImageUrl = "~/Images/ArrowUp.png";
                    }
                }
                else if (parameter == "Sort$UnitsInStock")
                {
                    if (ImgSortUnitsInStock.ImageUrl.Contains("ArrowUp.png"))
                    {
                        ImgSortUnitsInStock.ImageUrl = "~/Images/ArrowDown.png";
                        LitSortDirection.Text = "desc";
                    }
                    else
                    {
                        ImgSortUnitsInStock.ImageUrl = "~/Images/ArrowUp.png";
                    }
                }
                else if (parameter == "Sort$UnitsOnOrder")
                {
                    if (ImgSortUnitsOnOrder.ImageUrl.Contains("ArrowUp.png"))
                    {
                        ImgSortUnitsOnOrder.ImageUrl = "~/Images/ArrowDown.png";
                        LitSortDirection.Text = "desc";
                    }
                    else
                    {
                        ImgSortUnitsOnOrder.ImageUrl = "~/Images/ArrowUp.png";
                    }
                }
                else if (parameter == "Sort$ReorderLevel")
                {
                    if (ImgSortReorderLevel.ImageUrl.Contains("ArrowUp.png"))
                    {
                        ImgSortReorderLevel.ImageUrl = "~/Images/ArrowDown.png";
                        LitSortDirection.Text = "desc";
                    }
                    else
                    {
                        ImgSortReorderLevel.ImageUrl = "~/Images/ArrowUp.png";
                    }
                }
                else if (parameter == "Sort$Discontinued")
                {
                    if (ImgSortDiscontinued.ImageUrl.Contains("ArrowUp.png"))
                    {
                        ImgSortDiscontinued.ImageUrl = "~/Images/ArrowDown.png";
                        LitSortDirection.Text = "desc";
                    }
                    else
                    {
                        ImgSortDiscontinued.ImageUrl = "~/Images/ArrowUp.png";
                    }
                }
 
                // set all ImgSort images to spacer.gif
                if (parameter != "Sort$ProductID")
                    ImgSortProductID.ImageUrl = "~/Images/Spacer.gif";
 
                if (parameter != "Sort$ProductName")
                    ImgSortProductName.ImageUrl = "~/Images/Spacer.gif";
 
                if (parameter != "Sort$SupplierID")
                    ImgSortSupplierID.ImageUrl = "~/Images/Spacer.gif";
 
                if (parameter != "Sort$CategoryID")
                    ImgSortCategoryID.ImageUrl = "~/Images/Spacer.gif";
 
                if (parameter != "Sort$QuantityPerUnit")
                    ImgSortQuantityPerUnit.ImageUrl = "~/Images/Spacer.gif";
 
                if (parameter != "Sort$UnitPrice")
                    ImgSortUnitPrice.ImageUrl = "~/Images/Spacer.gif";
 
                if (parameter != "Sort$UnitsInStock")
                    ImgSortUnitsInStock.ImageUrl = "~/Images/Spacer.gif";
 
                if (parameter != "Sort$UnitsOnOrder")
                    ImgSortUnitsOnOrder.ImageUrl = "~/Images/Spacer.gif";
 
                if (parameter != "Sort$ReorderLevel")
                    ImgSortReorderLevel.ImageUrl = "~/Images/Spacer.gif";
 
                if (parameter != "Sort$Discontinued")
                    ImgSortDiscontinued.ImageUrl = "~/Images/Spacer.gif";
 
            }
        }
 
        private void SetPaging(string parameter)
        {
            if (!String.IsNullOrEmpty(parameter) && parameter.Contains("Page$"))
                LitCurrentPage.Text = parameter.Replace("Page$""");
 
            if (parameter != ListLastParam.Text)
            {
                if (IBtnCancelSearch.Visible)
                {
                    FillGridViewDataSourceUsingSearch();
                }
                else
                {
                    FillGridView((LitSortExpression.Text + " " + LitSortDirection.Text).Trim());
                    ListLastParam.Text = parameter;
 
                    int pageCount = (Products.GetRecordCount() - 1) / GridView1.PageSize + 1;
                    BuildPager(pageCount);
                }
            }
        }
 
        private void BuildPager(int pageCount)
        {
            int currentPage = Convert.ToInt32(LitCurrentPage.Text);
            int nearestTen = Functions.RoundToNearestTens(currentPage);
 
            StringBuilder pager = new StringBuilder();
            pager.Append("<table><tr>");
 
            if (nearestTen > 10)
            {
                int previousPage = nearestTen - 10;
                pager.Append("<td><a href='javascript:__doPostBack(&#39;ctl00$MainContent$GridView1&#39;,&#39;Page$1&#39;)' style='color:#333333;'>< First</a></td>");
                pager.Append("<td><a href='javascript:__doPostBack(&#39;ctl00$MainContent$GridView1&#39;,&#39;Page$" + previousPage + "&#39;)' style='color:#333333;'>...</a></td>");
            }
 
            for (int i = (nearestTen - 9); i <= nearestTen; i++)
            {
                if (i == currentPage)
                    pager.Append("<td><span style='font-size:12px;'>" + i + "</span></td>");
                else
                    pager.Append("<td><a href='javascript:__doPostBack(&#39;ctl00$MainContent$GridView1&#39;,&#39;Page$" + i + "&#39;)' style='color:#333333;'>" + i + "</a></td>");
 
                if (nearestTen > pageCount && i == pageCount)
                    break;
            }
 
            if (pageCount > nearestTen)
            {
                int nextPage = nearestTen + 1;
                pager.Append("<td><a href='javascript:__doPostBack(&#39;ctl00$MainContent$GridView1&#39;,&#39;Page$" + nextPage + "&#39;)' style='color:#333333;'>...</a></td>");
                pager.Append("<td><a href='javascript:__doPostBack(&#39;ctl00$MainContent$GridView1&#39;,&#39;Page$" + pageCount + "&#39;)' style='color:#333333;'>Last ></a></td>");
            }
 
            pager.Append("</tr></table>");
            LitPager.Text = pager.ToString();
        }
 
        private void FillGridView(string sortExpression)
        {
            int startRowIndex = (Convert.ToInt32(LitCurrentPage.Text) - 1) * GridView1.PageSize;
            GridView1.DataSource = Products.SelectSkipAndTake(GridView1.PageSize, startRowIndex, sortExpression);
            GridView1.DataBind();
        }
 
        protected void GridView1_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
        {
            Functions.GridViewRowDataBound(sender, e, 1);
        }
 
        protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
        {
            if (IBtnCancelSearch.Visible)
                FillGridViewDataSourceUsingSearch();
            else
                FillGridView((LitSortExpression.Text + " " + LitSortDirection.Text).Trim());
        }
 
        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            try
            {
                TableCell productID = GridView1.Rows[e.RowIndex].Cells[0];
                Products.Delete(Convert.ToInt32(productID.Text));
 
                if (IBtnCancelSearch.Visible)
                {
                    FillGridViewDataSourceUsingSearch();
                }
                else
                {
                    GridView1.DataSource = Products.SelectAll(LitSortExpression.Text + " " + LitSortDirection.Text);
                    GridView1.DataBind();
                }
 
            }
            catch (Exception ex)
            {
                e.Cancel = true;
                Functions.ShowModalError(ex, this);
            }
        }
 
        protected void IBtnSearch_Click(object sender, System.Web.UI.ImageClickEventArgs e)
        {
           if (IsSearchFieldsValid())
           {
               FillGridViewDataSourceUsingSearch(true);
 
               if (!IBtnCancelSearch.Visible)
                   IBtnCancelSearch.Visible = true;
           }
           else
           {
               Functions.ShowModalHtmlError(_validationErrors, this"Validation error occured");
           }
        }
 
        protected void IBtnCancelSearch_Click(object sender, ImageClickEventArgs e)
        {
           IBtnCancelSearch.Visible = false;
 
           // clear control values
           TxtProductID.Text = String.Empty;
           TxtProductName.Text = String.Empty;
           DdlSupplierID.SelectedValue = String.Empty;
           DdlCategoryID.SelectedValue = String.Empty;
           TxtQuantityPerUnit.Text = String.Empty;
           TxtUnitPrice.Text = String.Empty;
           TxtUnitsInStock.Text = String.Empty;
           TxtUnitsOnOrder.Text = String.Empty;
           TxtReorderLevel.Text = String.Empty;
           DdlDiscontinued.SelectedValue = String.Empty;
 
           // clear sorting and paging
           LitSortExpression.Text = String.Empty;
           LitSortDirection.Text = String.Empty;
 
           FillGridView(String.Empty);
 
           // reset paging
           int pageCount = (Products.GetRecordCount() - 1) / GridView1.PageSize + 1;
           BuildPager(pageCount);
 
           // clear sort images
           ImgSortProductID.ImageUrl = "~/Images/Spacer.gif";
           ImgSortProductName.ImageUrl = "~/Images/Spacer.gif";
           ImgSortSupplierID.ImageUrl = "~/Images/Spacer.gif";
           ImgSortCategoryID.ImageUrl = "~/Images/Spacer.gif";
           ImgSortQuantityPerUnit.ImageUrl = "~/Images/Spacer.gif";
           ImgSortUnitPrice.ImageUrl = "~/Images/Spacer.gif";
           ImgSortUnitsInStock.ImageUrl = "~/Images/Spacer.gif";
           ImgSortUnitsOnOrder.ImageUrl = "~/Images/Spacer.gif";
           ImgSortReorderLevel.ImageUrl = "~/Images/Spacer.gif";
           ImgSortDiscontinued.ImageUrl = "~/Images/Spacer.gif";
        }
 
        private bool IsSearchFieldsValid()
        {
            bool isValid = true;
            StringBuilder sb = new StringBuilder();
            _validationErrors = String.Empty;
 
            // check if at least one control has a value
            if(String.IsNullOrEmpty(TxtProductID.Text) && String.IsNullOrEmpty(TxtProductName.Text) && String.IsNullOrEmpty(DdlSupplierID.SelectedValue) && String.IsNullOrEmpty(DdlCategoryID.SelectedValue) && String.IsNullOrEmpty(TxtQuantityPerUnit.Text) && String.IsNullOrEmpty(TxtUnitPrice.Text) && String.IsNullOrEmpty(TxtUnitsInStock.Text) && String.IsNullOrEmpty(TxtUnitsOnOrder.Text) && String.IsNullOrEmpty(TxtReorderLevel.Text) && String.IsNullOrEmpty(DdlDiscontinued.SelectedValue))
            {
                sb.Append("- At least one search value must be filled<br>");
                isValid = false;
            }
            else
            {
                if (!String.IsNullOrEmpty(TxtProductID.Text))
                {
                    int productID;
                    bool isProductIDValid = Int32.TryParse(TxtProductID.Text, out productID);
 
                    if (!isProductIDValid)
                    {
                        sb.Append("- Product ID is an invalid number<br>");
                        isValid = false;
                    }
                }
 
                if (!String.IsNullOrEmpty(TxtUnitPrice.Text))
                {
                    decimal unitPrice;
                    bool isUnitPriceValid = Decimal.TryParse(TxtUnitPrice.Text, out unitPrice);
 
                    if (!isUnitPriceValid)
                    {
                        sb.Append("- Unit Price is an invalid number<br>");
                        isValid = false;
                    }
                }
 
                if (!String.IsNullOrEmpty(TxtUnitsInStock.Text))
                {
                    Int16 unitsInStock;
                    bool isUnitsInStockValid = Int16.TryParse(TxtUnitsInStock.Text, out unitsInStock);
 
                    if (!isUnitsInStockValid)
                    {
                        sb.Append("- Units In Stock is an invalid number<br>");
                        isValid = false;
                    }
                }
 
                if (!String.IsNullOrEmpty(TxtUnitsOnOrder.Text))
                {
                    Int16 unitsOnOrder;
                    bool isUnitsOnOrderValid = Int16.TryParse(TxtUnitsOnOrder.Text, out unitsOnOrder);
 
                    if (!isUnitsOnOrderValid)
                    {
                        sb.Append("- Units On Order is an invalid number<br>");
                        isValid = false;
                    }
                }
 
                if (!String.IsNullOrEmpty(TxtReorderLevel.Text))
                {
                    Int16 reorderLevel;
                    bool isReorderLevelValid = Int16.TryParse(TxtReorderLevel.Text, out reorderLevel);
 
                    if (!isReorderLevelValid)
                    {
                        sb.Append("- Reorder Level is an invalid number<br>");
                        isValid = false;
                    }
                }
 
            }
 
            if (!isValid)
                _validationErrors = sb.ToString();
 
            return isValid;
        }
 
        private void FillGridViewDataSourceUsingSearch(bool isFromSearchButton = false)
        {
            // everything is nullable, only items being searched for should be filled
            int? productID = null;
            string productName = null;
            int? supplierID = null;
            int? categoryID = null;
            string quantityPerUnit = null;
            decimal? unitPrice = null;
            Int16? unitsInStock = null;
            Int16? unitsOnOrder = null;
            Int16? reorderLevel = null;
            bool? discontinued = null;
 
            if (!String.IsNullOrEmpty(TxtProductID.Text))
                productID = Convert.ToInt32(TxtProductID.Text);
 
            if (!String.IsNullOrEmpty(TxtProductName.Text))
                productName = TxtProductName.Text;
 
            if (!String.IsNullOrEmpty(DdlSupplierID.SelectedValue))
                supplierID = Convert.ToInt32(DdlSupplierID.SelectedValue);
 
            if (!String.IsNullOrEmpty(DdlCategoryID.SelectedValue))
                categoryID = Convert.ToInt32(DdlCategoryID.SelectedValue);
 
            if (!String.IsNullOrEmpty(TxtQuantityPerUnit.Text))
                quantityPerUnit = TxtQuantityPerUnit.Text;
 
            if (!String.IsNullOrEmpty(TxtUnitPrice.Text))
                unitPrice = Convert.ToDecimal(TxtUnitPrice.Text);
 
            if (!String.IsNullOrEmpty(TxtUnitsInStock.Text))
                unitsInStock = Convert.ToInt16(TxtUnitsInStock.Text);
 
            if (!String.IsNullOrEmpty(TxtUnitsOnOrder.Text))
                unitsOnOrder = Convert.ToInt16(TxtUnitsOnOrder.Text);
 
            if (!String.IsNullOrEmpty(TxtReorderLevel.Text))
                reorderLevel = Convert.ToInt16(TxtReorderLevel.Text);
 
            if (!String.IsNullOrEmpty(DdlDiscontinued.SelectedValue))
                discontinued = Convert.ToBoolean(DdlDiscontinued.SelectedValue);
 
            string sortExpression = (LitSortExpression.Text + " " + LitSortDirection.Text).Trim();
            string parameter = Request["__EVENTARGUMENT"];
            int totalRowCount;
            int startRowIndex;
 
            if (isFromSearchButton || (!String.IsNullOrEmpty(parameter) && parameter.Contains("Sort$")))
            {
                startRowIndex = 0;
                LitCurrentPage.Text = "1";
            }
            else
                startRowIndex = (Convert.ToInt32(LitCurrentPage.Text) - 1) * GridView1.PageSize;
 
            GridView1.DataSource = Products.SelectSkipAndTakeDynamicWhere(productID, productName, supplierID, categoryID, quantityPerUnit, unitPrice, unitsInStock, unitsOnOrder, reorderLevel, discontinued, GridView1.PageSize, startRowIndex, out totalRowCount, sortExpression);
            GridView1.DataBind();
 
            int pageCount = (totalRowCount - 1) / GridView1.PageSize + 1;
            BuildPager(pageCount);
        }
 
        public SuppliersCollection GetSuppliersDropDownListData()
        {
            return Suppliers.SelectSuppliersDropDownListData();
        }
 
        public CategoriesCollection GetCategoriesDropDownListData()
        {
            return Categories.SelectCategoriesDropDownListData();
        }
    }
}