using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.OleDb;
using System.Configuration;
using DataAccess;
using System.Data.OracleClient;

namespace VMT
{
    public partial class CycleMgmt : System.Web.UI.Page
    {
        string m_SP_VDM_SELECT_BSUNIT_FORECAST = Properties.Settings.Default.SP_VDM_SELECT_BSUNIT_FORECAST;
        string m_SP_VDM_SELECT_YEAR_FORECAST = Properties.Settings.Default.SP_VDM_SELECT_YEAR_FORECAST;

        string m_SP_VDM_SELECT_MILES_AMT_YR_EC = Properties.Settings.Default.SP_VDM_SELECT_MILES_AMT_YR_EC;

        double milesTotal = 0.00;
        double amountTotal = 0.00;

        string userRole = string.Empty;
        string m_SP_UR_GET_USER_ACCESS = Properties.Settings.Default.SP_UR_GET_USER_ACCESS;
        string pageName = "Project Analysis";

        protected void Page_Load(object sender, EventArgs e)
        {
           

            ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page);
            scriptManager.RegisterPostBackControl(this.btnExportExcel);
            if (!Page.IsPostBack)
            {

                //checks user role
                //userRole = DataAccessUtility.GetRole(m_SP_UR_GET_USER_ACCESS, pageName);
                userRole = VMT.UserRole.CallNewUserRoleWebService(m_SP_UR_GET_USER_ACCESS, pageName, System.Web.HttpContext.Current.User.Identity.Name.ToUpper());

                if (userRole == "0")
                {
                    Response.Redirect("default.aspx");
                }

                BindBusinessUnit();
                //BindTotMilesAndGrid();
                BindYear(ddl_Year);
                ViewState["years"] = "";
            }
        }

        void BindBusinessUnit()
        {
            try
            {
                DataAccessUtility.BindDropdownListWithoutConditionViaProcedure(m_SP_VDM_SELECT_BSUNIT_FORECAST, ddl_Bunit);
                ddl_Bunit.SelectedValue = "2";
            }
            catch
            {
            }
        }

        

        //protected void ddl_Bunit_DataBound(object sender, EventArgs e)
        //{
        //    BindYear(ddl_Year);
            
        //}

        void BindYear(DropDownList ddlYear)
        {
            int V_BUSINESS_UNIT_ID = 0;
            try
            {
                V_BUSINESS_UNIT_ID = Convert.ToInt32(ddl_Bunit.SelectedValue);
                //DataAccessUtility.BindDropdownListWithoutConditionViaProcedure(m_SP_VDM_SELECT_YEAR_FORECAST, ddlYear);
                //ddlYear.SelectedValue = "16";
                List<OleDbParameter> OledbParams = new List<OleDbParameter>();
                OledbParams.Add(new OleDbParameter("V_BUSINESS_UNIT_ID", V_BUSINESS_UNIT_ID));
                DataAccessUtility.BindDropdownListWithConditionViaProcedure(m_SP_VDM_SELECT_YEAR_FORECAST, OledbParams, ddl_Year);
                ddlYear.SelectedValue = DateTime.Now.Year.ToString().Substring(DateTime.Now.Year.ToString().Length - 2);
            }
            catch
            {
            }
        }

        void BindTotMilesAndGrid()
        {
            List<OleDbParameter> OledbParams = new List<OleDbParameter>();
            try
            {
                int V_BUSINESS_UNIT_ID = 0;
                V_BUSINESS_UNIT_ID = Convert.ToInt32(ddl_Bunit.SelectedValue);
                OledbParams.Add(new OleDbParameter("V_BUSINESS_UNIT_ID", V_BUSINESS_UNIT_ID));
                OledbParams.Add(new OleDbParameter("V_YEARS", ViewState["years"].ToString().Trim()));
                DataAccessUtility.BindGridViewViaProcedureWithParameter(m_SP_VDM_SELECT_MILES_AMT_YR_EC, OledbParams, gdv_TotMilesAmt);
                gdv_TotMilesAmt.SelectedIndex = -1;
                if (gdv_TotMilesAmt.Rows.Count > 0)
                {
                    btnRest.Visible = true;
                    btnExportExcel.Visible = true;
                    DataSet ds = gdv_TotMilesAmt.DataSource as DataSet;
                    ViewState["dsTotMilesGrid"] = gdv_TotMilesAmt.DataSource as DataSet;
                    BindSummaryGrid();
                }
                else
                {
                    btnRest.Visible = false;
                    btnExportExcel.Visible = false;
                }
            }
            catch
            {
            }
        }

        void BindSummaryGrid()
        {
           // DataSet ds = gdv_TotMilesAmt.DataSource as DataSet;
           // ViewState["dsTotMilesGrid"] = gdv_TotMilesAmt.DataSource as DataSet;
            try
            {
                DataSet ds = (DataSet)ViewState["dsTotMilesGrid"];
                DataView dv = new DataView(ds.Tables[0]);

                DataTable dt = dv.ToTable(true, new string[] { "Year" });
                dt.Columns.Add("Total_Miles", typeof(double));
                dt.Columns.Add("Total_Amount", typeof(double));
                foreach (DataRow dr in dt.Rows)
                {

                    dr["Total_Miles"] = ds.Tables[0].Compute("Sum(" + "Total_Miles" + ")", "YEAR" + " = '" + dr["YEAR"] + "'");
                    dr["Total_Amount"] = ds.Tables[0].Compute("Sum(" + "Total_Amount" + ")", "YEAR" + " = '" + dr["YEAR"] + "'");
                }

                //var result = from b in dt.AsEnumerable()
                //                  group b by b.Field<int>("YEAR") into g
                //                  let list = g.ToList()
                //                  select new
                //                  {
                //                      YEAR = g.Key,
                //                      Toatl_Miles = list.Sum(x => x.Field<int>("Total_Miles"))
                //                  };

                dt.DefaultView.Sort = "YEAR DESC";
                gdvSummary.DataSource = dt;
                gdvSummary.DataBind();
            }
            catch
            {
            }
        }

        protected void gdvSummary_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Header)
            {
                e.Row.Cells[1].HorizontalAlign = HorizontalAlign.Right;
                e.Row.Cells[2].HorizontalAlign = HorizontalAlign.Right;
            }

            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                    e.Row.Cells[1].HorizontalAlign = HorizontalAlign.Right;
                    e.Row.Cells[2].HorizontalAlign = HorizontalAlign.Right;               
            }
        }
           
        
    
        protected void btn_add_Click(object sender, EventArgs e)
        {
            GetYears();
            BindTotMilesAndGrid();
        }

        protected void btnRest_Click(object sender, EventArgs e)
        {
            Reset();
        }

        void Reset()
        {
            gdv_TotMilesAmt.DataSource = null;
            gdv_TotMilesAmt.DataBind();
            gdvSummary.DataSource = null;
            gdvSummary.DataBind();
            //BindBusinessUnit();
            BindYear(ddl_Year);
            btnRest.Visible = false;
            ViewState["years"] = "";
            btnExportExcel.Visible = false;
        }

        protected void ddl_Year_SelectedIndexChanged(object sender, EventArgs e)
        {

            //GetYears();
        }

        void GetYears()
        {
            if (ViewState["years"].ToString().Trim().Length > 0)
            {
                ViewState["years"] = ViewState["years"] + "," + ddl_Year.SelectedValue;
            }
            else
            {
                ViewState["years"] = ddl_Year.SelectedValue;
            }
            if (ddl_Year.Items.Count >0)
                ddl_Year.Items.RemoveAt(ddl_Year.SelectedIndex);
           

        }

        protected void txtYear_TextChanged(object sender, EventArgs e)
        {
            try
            {
                GridViewRow gvRow = (GridViewRow)(sender as Control).Parent.Parent;
                int index = gvRow.RowIndex;
                DataSet ds = (DataSet)ViewState["dsTotMilesGrid"];
                DataView dv = new DataView(ds.Tables[0]);
                DataTable dt = dv.ToTable();
                if (((TextBox)gdv_TotMilesAmt.Rows[index].FindControl("txtYear")).Text.Trim().Length > 0)
                {

                    ds.Tables[0].Rows[index]["YEAR"] = ((TextBox)gdv_TotMilesAmt.Rows[index].FindControl("txtYear")).Text.Trim();

                    dt.AcceptChanges();
                    ViewState["dsTotMilesGrid"] = ds;
                    BindSummaryGrid();
                }
                else
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Year can not be blank!')", true);
                    ((TextBox)gdv_TotMilesAmt.Rows[index].FindControl("txtYear")).Focus();
                    return;
                }
            }
            catch
            {
            }
        }

        protected void ddl_Bunit_SelectedIndexChanged(object sender, EventArgs e)
        {
            Reset();
        }


       
        //public string SortDireaction
        //{
        //    get
        //    {
        //        if (ViewState["SortDireaction"] == null)
        //            return string.Empty;
        //        else
        //            return ViewState["SortDireaction"].ToString();
        //    }
        //    set
        //    {
        //        ViewState["SortDireaction"] = value;
        //    }
        //}

       // private string _sortDirection;
        protected void gdv_TotMilesAmt_Sorting(object sender, GridViewSortEventArgs e)
        { 
            VDMUtil.GridviewSorting(gdv_TotMilesAmt, e.SortExpression, (DataSet)ViewState["dsTotMilesGrid"]);
            //ViewState["SortDireaction"] = str;
            //DataSet ds = (DataSet)ViewState["dsTotMilesGrid"];
            //DataView dv = new DataView(ds.Tables[0]);
            //DataTable dataTable = dv.ToTable();
            //if (dataTable != null)
            //{
            //    //Sort the data.
            //    dataTable.DefaultView.Sort = e.SortExpression + " " + _sortDirection;
            //    gdv_TotMilesAmt.DataSource = dataTable;
            //    gdv_TotMilesAmt.DataBind();
            //  SortDireaction = _sortDirection;
            //    int columnIndex = 0;
            //    foreach (DataControlFieldHeaderCell headerCell in gdv_TotMilesAmt.HeaderRow.Cells)
            //    {
            //        if (headerCell.ContainingField.SortExpression == e.SortExpression)
            //        {
            //            columnIndex = gdv_TotMilesAmt.HeaderRow.Cells.GetCellIndex(headerCell);
            //        }
            //    }

            //    gdv_TotMilesAmt.HeaderRow.Cells[columnIndex].Controls.Add(sortImage);
            //}
        }

        //protected void SetSortDirection(string sortDirection)
        //{
        //    if (sortDirection == "ASC")
        //    {
        //        _sortDirection = "DESC";
        //        sortImage.ImageUrl = "resource_gallery/graphics/downarrow.png";
        //    }
        //    else
        //    {
        //        _sortDirection = "ASC";
        //        sortImage.ImageUrl = "resource_gallery/graphics/uparrow.png";
        //    }
        //}
             
        protected void btnExportExcel_Click(object sender, EventArgs e)
        {
            try
            {
                Dictionary<string, string> dictionaryFilters = new Dictionary<string, string>();
                dictionaryFilters.Add("Business Unit", ddl_Bunit.SelectedItem.Text);
                dictionaryFilters.Add("Year", ddl_Year.SelectedItem.Text);
                List<int> listColumnIndex = new List<int>(new int[] { });
                VDMUtil.ExportGridToExcel(gdv_TotMilesAmt, "Cycle Management", "Cycle_Management", dictionaryFilters, listColumnIndex);
            }
            catch
            {
            }
        }
        public override void VerifyRenderingInServerForm(Control control)
        {
            /* Confirms that an HtmlForm control is rendered for the specified ASP.NET
               server control at run time. */
        }


        //protected void ddlYear_SelectedIndexChanged(object sender, EventArgs e)
        //{
        //    GridViewRow gvRow = (GridViewRow)(sender as Control).Parent.Parent;
        //    int index = gvRow.RowIndex;
        //    DataSet ds = (DataSet)ViewState["dsTotMilesGrid"];
        //    DataView dv = new DataView(ds.Tables[0]);
        //    DataTable dt = dv.ToTable();


        //    ds.Tables[0].Rows[index]["YEAR"] = ((DropDownList)gdv_TotMilesAmt.Rows[index].FindControl("ddlYear")).Text.Trim();

        //    dt.AcceptChanges();
        //    ViewState["dsTotMilesGrid"] = ds;
        //    BindSummaryGrid();
            
        //}

        //protected void ddlYear_DataBound(object sender, EventArgs e)
        //{
        //    BindYear(ddl_Year);
        //}

        //protected void gdv_TotMilesAmt_RowDataBound(object sender, GridViewRowEventArgs e)
        //{
        //    if (e.Row.RowType == DataControlRowType.DataRow)
        //    {
        //        DropDownList ddlDropDownList = (DropDownList)e.Row.FindControl("ddlYear");

        //        if (ddlDropDownList != null)
        //        {
        //            BindYear(ddlDropDownList);
        //        }
        //    }

        //}  
    }
}