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 System.Data.SqlClient;
using DataAccess;
using System.IO;
namespace VMT
{
    public partial class OpenForContractor : System.Web.UI.Page
    {
        string m_SP_VDM_SELECT_BUSINESS_UNIT = Properties.Settings.Default.SP_VDM_SELECT_BUSINESS_UNIT;
        string m_SP_VDM_SELECT_YEAR_BU_OC = Properties.Settings.Default.SP_VDM_SELECT_YEAR_BU_OC;
        //string m_SP_VDM_SELECT_ALL_EVENTCODE = Properties.Settings.Default.SP_VDM_SELECT_ALL_EVENTCODE;
        string m_SP_VDM_SELECT_EVENTCODE_OC = Properties.Settings.Default.SP_VDM_SELECT_EVENTCODE_OC;
        string m_SP_VDM_SELECT_COMAPANY = Properties.Settings.Default.SP_VDM_SELECT_COMAPANY_OC;        
        string m_SP_VDM_SELECT_OPEN_CONTRACTOR = Properties.Settings.Default.SP_VDM_SELECT_OPEN_CONTRACTOR;
        string m_SP_VDM_UPDATE_OPEN_CONT_STATUS = Properties.Settings.Default.SP_VDM_UPDATE_OPEN_CONT_STATUS;
        string m_SP_VDM_UPD_OPEN_CONT_ACTIVATE = Properties.Settings.Default.SP_VDM_UPD_OPEN_CONT_ACTIVATE;

        string scanaId = System.Web.HttpContext.Current.User.Identity.Name.ToUpper();
        string userRole = string.Empty;
        string m_SP_UR_GET_USER_ACCESS = Properties.Settings.Default.SP_UR_GET_USER_ACCESS;
        string pageName = "Open Work for Contractor";

        protected void Page_Load(object sender, EventArgs e)
        {

            if (Page.IsPostBack)
            {
                ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "afterpostback();", true);
            }
            ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page);
            scriptManager.RegisterPostBackControl(this.btnExportExcel);
            if (!Page.IsPostBack)
            {

                //checks user role


                if (Properties.Settings.Default.ENVMNT.ToString() == "LOCAL")
                {
                    userRole = VMT.UserRole.CallNewUserRoleWebService(m_SP_UR_GET_USER_ACCESS, pageName, System.Environment.UserName.ToUpper());
                }
                else
                {
                    userRole = VMT.UserRole.CallNewUserRoleWebService(m_SP_UR_GET_USER_ACCESS, pageName, System.Web.HttpContext.Current.User.Identity.Name.ToUpper());
                }
                hdn_role.Value = userRole;
                BindBusinessUnit();
                ddlBUnit.SelectedValue = Properties.Settings.Default.SELECTED_BUNIT;
                BindYear();
                // ddlYear.SelectedValue = DateTime.Now.Year.ToString().Substring(DateTime.Now.Year.ToString().Length - 2);
                //BindEventCode();
                //BindGrid();
            }
        }

        void BindBusinessUnit()
        {
            try
            {
                DataAccessUtility.BindDropdownListWithoutConditionViaProcedure(m_SP_VDM_SELECT_BUSINESS_UNIT, ddlBUnit);
            }
            catch
            {
            }
        }

        void BindYear()
        {
            try
            {
               
                int V_BUSINESS_UNIT_ID = 0;               

                V_BUSINESS_UNIT_ID = Convert.ToInt32(ddlBUnit.SelectedValue);           

                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_BU_OC, OledbParams, ddlYear);
            }
            catch
            {
            }

           
        }

        void BindEventCode()
        {
            try
            {
                int V_BUSINESS_UNIT_ID = 0;
                int V_YEAR = 0;

                V_BUSINESS_UNIT_ID = Convert.ToInt32(ddlBUnit.SelectedValue);
                V_YEAR = Convert.ToInt32(ddlYear.SelectedValue);

                List<OleDbParameter> OledbParams = new List<OleDbParameter>();
                OledbParams.Add(new OleDbParameter("V_BUSINESS_UNIT_ID", V_BUSINESS_UNIT_ID));
                OledbParams.Add(new OleDbParameter("V_YEAR", V_YEAR));
                DataAccessUtility.BindDropdownListWithConditionViaProcedure(m_SP_VDM_SELECT_EVENTCODE_OC, OledbParams, ddlEventCode);
            }
            catch
            {
            }
            

        }
        void BindCompany()
        {
            try
            {
                int V_BUSINESS_UNIT_ID = 0;
                int V_YEAR = 0;
                int V_EVENT_CODE_ID = 0;

                V_BUSINESS_UNIT_ID = Convert.ToInt32(ddlBUnit.SelectedValue);
                V_YEAR = Convert.ToInt32(ddlYear.SelectedValue);
                V_EVENT_CODE_ID = Convert.ToInt32(ddlEventCode.SelectedValue);
                List<OleDbParameter> OledbParams = new List<OleDbParameter>();
                OledbParams.Add(new OleDbParameter("V_BUSINESS_UNIT_ID", V_BUSINESS_UNIT_ID));
                OledbParams.Add(new OleDbParameter("V_YEAR", V_YEAR));
                OledbParams.Add(new OleDbParameter("V_EVENT_CODE_ID", V_EVENT_CODE_ID));
                DataAccessUtility.BindDropdownListWithConditionViaProcedure(m_SP_VDM_SELECT_COMAPANY, OledbParams, ddlCompany);
            }
            catch
            {
            }


        }

        void BindGrid()
        {
            try
            {
                int V_BUSINESS_UNIT_ID = 0;
                int V_YEAR = 0;
                int V_EVENT_CODE_ID = 0;
                int V_COMPANY_ID = 0;
                V_BUSINESS_UNIT_ID = Convert.ToInt32(ddlBUnit.SelectedValue);
                V_YEAR = Convert.ToInt32(ddlYear.SelectedValue);
                V_EVENT_CODE_ID = Convert.ToInt32(ddlEventCode.SelectedValue);
                V_COMPANY_ID = Convert.ToInt32(ddlCompany.SelectedValue);
                
                List<OleDbParameter> OledbParams = new List<OleDbParameter>();
                OledbParams.Add(new OleDbParameter("V_BUSINESS_UNIT_ID", V_BUSINESS_UNIT_ID));
                OledbParams.Add(new OleDbParameter("V_YEAR", V_YEAR));
                OledbParams.Add(new OleDbParameter("V_EVENT_CODE_ID", V_EVENT_CODE_ID));
                OledbParams.Add(new OleDbParameter("V_COMPANY_ID", V_COMPANY_ID));
                DataAccessUtility.BindGridViewWithConditionViaProcedure(m_SP_VDM_SELECT_OPEN_CONTRACTOR, OledbParams, gdvOpenContractor);
                ViewState["dataTable"] = gdvOpenContractor.DataSource as DataSet;
                gdvOpenContractor.SelectedIndex = -1;

                if (gdvOpenContractor.Rows.Count > 0)
                {
                    //btnSave.Visible = true;
                    btnExportExcel.Visible = true;
                }
                else
                {
                   // btnSave.Visible = false;
                    btnExportExcel.Visible = false;
                }

                //checks user role
                //userRole = DataAccessUtility.GetCurrentUserRoles(scanaId);
                if (gdvOpenContractor.Rows.Count > 0 && hdn_role.Value == "2")
                {
                    btnSave.Visible = true;
                }
                else if (gdvOpenContractor.Rows.Count > 0 && hdn_role.Value == "3")
                {
                    btnSave.Visible = true;
                }
                else if (gdvOpenContractor.Rows.Count > 0 && hdn_role.Value == "1")
                {
                    btnSave.Visible = false;
                }
                else if (hdn_role.Value == "0")
                {
                    Response.Redirect("Default.aspx");
                }
            }

            catch
            {
            }
            
            
        }

        protected void ddlBUnit_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindYear();
            //BindEventCode();
        }

        protected void ddlYear_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindEventCode();
        }

        protected void ddlEventCode_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindCompany();
        }

        //protected void btnGo_Click(object sender, EventArgs e)
        //{
        //    BindGrid();
        //}

        

        protected void cbSelectAll_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox ChkBoxHeader = (CheckBox)gdvOpenContractor.HeaderRow.FindControl("cbSelectAll");
            foreach (GridViewRow row in gdvOpenContractor.Rows)
            {
                CheckBox ChkBoxRows = (CheckBox)row.FindControl("cbSelect");
                if (ChkBoxRows.Enabled == true)
                {
                    if (ChkBoxHeader.Checked == true)
                    {
                        ChkBoxRows.Checked = true;
                    }
                    else
                    {
                        ChkBoxRows.Checked = false;
                    }
                }
            }
        }

       
        protected void btnExportExcel_Click(object sender, EventArgs e)
        {
            try
            {
                Dictionary<string, string> dictionaryFilters = new Dictionary<string, string>();
                dictionaryFilters.Add("Business Unit", ddlBUnit.SelectedItem.Text);
                dictionaryFilters.Add("Year", ddlYear.SelectedItem.Text);
                dictionaryFilters.Add("Event Code", ddlEventCode.SelectedItem.Text);
                List<int> listHideColumns = new List<int>(new int[] { 3,5 });
                VDMUtil.ExportGridToExcel(gdvOpenContractor, "Open for Contractor", "Open_for_Contractor", dictionaryFilters, listHideColumns);
            }
            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 btnSave_Click(object sender, EventArgs e)
        {
            int retVal = 0;
            int V_WORK_AREA_ID ;
            int V_WORK_STATUS_ID;
            int V_COMPANY_ID;
            foreach (GridViewRow row in gdvOpenContractor.Rows)
            {
                if (((CheckBox)row.FindControl("cbSelect")).Checked)
                {
                    
                   V_WORK_AREA_ID  = Convert.ToInt32(((Label)row.FindControl("lbl_WORK_AREA_ID")).Text);
                   V_WORK_STATUS_ID = 4;
                }

                else{
                    V_WORK_AREA_ID  = Convert.ToInt32(((Label)row.FindControl("lbl_WORK_AREA_ID")).Text);
                   V_WORK_STATUS_ID = 3;
                }

                V_COMPANY_ID = Convert.ToInt32(((Label)row.FindControl("lbl_COMPANY_ID")).Text);
                try
                {
                    List<OleDbParameter> sqlParams = new List<OleDbParameter>();
                    //sqlParams.Add(new OleDbParameter("V_COMPANY_ID", V_COMPANY_ID));
                    sqlParams.Add(new OleDbParameter("V_WORK_AREA_ID", V_WORK_AREA_ID));
                    sqlParams.Add(new OleDbParameter("V_WORK_STATUS_ID", V_WORK_STATUS_ID));
                    sqlParams.Add(new OleDbParameter("V_LAST_UPDATED_USER_ID", System.Web.HttpContext.Current.User.Identity.Name.Replace("SCANA\\", "").ToUpper()));
                    retVal = DataAccessUtility.InsertUpdateDeleteViaStoreProcedureParam(m_SP_VDM_UPDATE_OPEN_CONT_STATUS, sqlParams);
                }
                catch
                {
                }
            }

            if (retVal == 1)
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Update successful')", true);
            }
            else
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('No update done')", true);
            }
            BindGrid();
        }

        protected void gdvOpenContractor_Sorting(object sender, System.Web.UI.WebControls.GridViewSortEventArgs e)
        {
            try
            {
                VDMUtil.GridviewSorting(gdvOpenContractor, e.SortExpression, (DataSet)ViewState["dataTable"]);
            }
            catch
            {
            }
        }

        protected void ddlEventCode_DataBound(object sender, EventArgs e)
        {
            BindCompany();
        }

        protected void ddlYear_DataBound(object sender, EventArgs e)
        {
            BindEventCode();
        }

        protected void ddlCompany_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindGrid();
        }

        protected void ddlCompany_DataBound(object sender, EventArgs e)
        {
            BindGrid();
        }

        protected void cbSelect_CheckedChanged(object sender, EventArgs e)
        {
            //int i = 0;
            int RowIndex = ((sender as CheckBox).NamingContainer as GridViewRow).RowIndex;
            string waId = ((Label)(gdvOpenContractor.Rows[RowIndex].FindControl("lbl_WORK_AREA_ID"))).Text;
            CheckBox cbx = ((CheckBox)(gdvOpenContractor.Rows[RowIndex].FindControl("cbSelect")));
            foreach (GridViewRow row in gdvOpenContractor.Rows)
            {
                //string workareaId = ((Label)(gdvOpenContractor.Rows[RowIndex].FindControl("lbl_WORK_AREA_ID"))).Text;
                Label lblWAId = (Label)row.FindControl("lbl_WORK_AREA_ID");
                string workareaId = lblWAId.Text;
                CheckBox ChkBoxRows = (CheckBox)row.FindControl("cbSelect");

                if (cbx.Checked == true && workareaId == waId)
                {
                    ChkBoxRows.Checked = true;
                    //i++;
                }
                else if (cbx.Checked == false && workareaId == waId)
                {
                    ChkBoxRows.Checked = false;
                    //i++;
                }

                //if (i > 0)
                //{
                //    ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Multiple Contractor assigned to this workarea.')", true);
                //}
            }
        }

        protected void gdvOpenContractor_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            int retVal = 0;
            if (e.CommandName == "Select")
            {
                //Determine the RowIndex of the Row whose Button was clicked.
                int rowIndex = Convert.ToInt32(e.CommandArgument);

                //Reference the GridView Row.
                GridViewRow row = gdvOpenContractor.Rows[rowIndex];

                //Fetch value

                string V_OPEN_STS = Convert.ToString((row.FindControl("hdn_open") as HiddenField).Value);
                string V_WA_STS = Convert.ToString((row.FindControl("hdn_status") as HiddenField).Value);
                if (V_OPEN_STS == "false")
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Could not be activated or in-activated as WORKAREA / SECTION is in " + V_WA_STS + " status.')", true);
                    return;
                }

                int V_WORKAREA_ID = Convert.ToInt32((row.FindControl("lbl_WORK_AREA_ID") as Label).Text);
                int V_COMPANY_ID = Convert.ToInt32((row.FindControl("lbl_COMPANY_ID") as Label).Text);
                string V_ACTIVE_STATUS = (row.FindControl("btnActive") as Button).Text;
                if (V_ACTIVE_STATUS == "Active")
                    V_ACTIVE_STATUS = "In-Active";
                else
                    V_ACTIVE_STATUS = "Active";

                try
                {
                    List<OleDbParameter> sqlParams = new List<OleDbParameter>();
                    sqlParams.Add(new OleDbParameter("V_WORKAREA_ID", V_WORKAREA_ID));
                    sqlParams.Add(new OleDbParameter("V_COMPANY_ID", V_COMPANY_ID));
                    sqlParams.Add(new OleDbParameter("V_ACTIVE_STATUS", V_ACTIVE_STATUS));
                    sqlParams.Add(new OleDbParameter("V_LAST_UPDATED_USER_ID", System.Web.HttpContext.Current.User.Identity.Name.Replace("SCANA\\", "").ToUpper()));
                    retVal = DataAccessUtility.InsertUpdateDeleteViaStoreProcedureParam(m_SP_VDM_UPD_OPEN_CONT_ACTIVATE, sqlParams);
                    BindGrid();
                }
                catch
                {
                }
            }
        }

    }
}