using System;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace CH78
{
    public partial class Home : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            
            Page.ClientScript.RegisterClientScriptInclude("Test", "MyScript.js");

// Page.
            gvStudent.RowDataBound += new GridViewRowEventHandler(grdStudent_RowDataBound); //row databound event
            gvStudent.PageIndexChanging += new GridViewPageEventHandler(grdStudent_PageIndexChanging);
            gvStudent.Sorting += new GridViewSortEventHandler(grdStudent_Sorting);

            if (!IsPostBack)
            {

            }

            
        }

        private void grdStudent_Sorting(object sender, GridViewSortEventArgs e)
        {
            SortRecords(e.SortExpression);
        }

        public string sortDir
        {
            get => (string)ViewState["sortDir"];
            set => ViewState["sortDir"] = value;
        }

        private void SortRecords(string sortExpress)
        {
            string oldExpression = gvStudent.SortExpression;
            String newExpression = sortExpress;
            String lastValue, theSortField;
            String sortExpression;
            DataView source;
            String theDirection;

            string oldSortExp, newSortExp;

            string wildChar;
            theDirection = " ";
            wildChar = " %";

            lastValue = (string) ViewState["sortValue"];
            sortExpression = sortExpress;

            oldSortExp = (string)ViewState["oldSortExpression"];

            //get the last sort field and the new sort field
            // if (oldSortExp != sortExpression) //check for new expression, that is DB field
            // {
                if (this.sortDir == "desc")
                {
                    this.sortDir = "asc";
                }
                else if (this.sortDir == null)
                {
                    this.sortDir = "asc";
                }
                else if (this.sortDir == "asc")
                {
                    this.sortDir = "desc";
                }
                else  //sort in ascending order the first time, column may not change if already sorted that way
                {
                    this.sortDir = "asc";
                }
                theSortField = (string)ViewState["sortField"];

                source = (DataView)Cache["StudentData"]; // use the cache

                source.Sort = (" " + sortExpression + " " + this.sortDir);

                ViewState["oldSortExpression"] = sortExpress; // save the sort as old sort

                gvStudent.DataSource = source;
                gvStudent.DataBind();
            // }
            
        }
        
        private void grdStudent_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {

            Int32 pageNum = 0;
            pageNum = e.NewPageIndex;
            if (txtStudentID.Text.Trim().Length > 0 || txtFName.Text.Trim().Length > 0 || txtLName.Text.Trim().Length > 0)
            {
                textHasValues = true;
            }
            Paging(pageNum);
            

        }

        private void Paging(Int32 page)
        {
            gvStudent.PageIndex = page;
            BindData();
        }

        private void BindData()
        {
            
            DataSet ds = new DataSet();

            string stuID = Convert.ToString(Session["vStuID"]);
            string LNAME = Convert.ToString(Session["vLNAME"]);
            string FNAME = Convert.ToString(Session["vFNAME"]);

            txtStudentID.Text = stuID;
            txtFName.Text = FNAME;
            txtLName.Text = LNAME;

            if (textHasValues)
            {
                ds = StudentDataTier.SearchStudents(FNAME, LNAME, stuID);
            }
            
            
            // ds = dt.GetStudents();
            gvStudent.DataSource = ds.Tables[0];

            if (Cache["StudentData"] == null)
            {
                Cache.Add("StudentData", new DataView(ds.Tables[0]),
                    null,System.Web.Caching.Cache.NoAbsoluteExpiration,
                    System.TimeSpan.FromMinutes(10), System.Web.Caching.CacheItemPriority.Default,
                    null);
            }
            gvStudent.DataBind();
            
        }

        protected void grdStudent_RowDataBound(Object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Header) // header add click event to select checkboxes
            {
                ((CheckBox)e.Row.FindControl("cbSelectAll")).Attributes.Add("onclick", "javascript:SelectAll('" + ((CheckBox)e.Row.FindControl("cbSelectAll")).ClientID + "')");
            }
        }

        private bool textHasValues = false;
        protected void btnSearch_Click(object sender, EventArgs e)
        {

            if (txtStudentID.Text.Trim().Length > 0 || txtFName.Text.Trim().Length > 0 || txtLName.Text.Trim().Length > 0)
            {

                
                try
                {

                    Session["vStuID"] = txtStudentID.Text.Trim();
                    Session["vFNAME"] = txtFName.Text.Trim();
                    Session["vLNAME"] = txtLName.Text.Trim();

                    Cache.Remove("StudentData");
                    textHasValues = true;
                    BindData();
                    
                    
                    
                }
                catch (Exception exception)
                {

                    

                }
                
            }

        }

        protected void grdStudent_SelectedIndexChanged(object sender, EventArgs e)
        {
           
        }

        protected void Delete_Click(object sender, CommandEventArgs e)
        {

        }

        protected void lbtnEdit_Click(object sender, CommandEventArgs e)
        {
            
        }
    }
}