using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Threading;
using System.Reflection;
using System.Resources;
using System.Globalization;
public partial class Transactions_TA_UI_Transaction_ShiftAllocationDelete : Base.BasePage
{
    #region "Variable Declaration"
    ResourceManager rm;
    CultureInfo ci;
    ShiftAllocationEvendata objShiftAllocation = new ShiftAllocationEvendata();
    cls_Common objcls_Common = new cls_Common();
    //DataSet ds_Empdetails = new DataSet();
    DateTime dtFromdate, dtTodate;
    int gintUserId;
    string gstrDateFormat;
    LeaveApplicationEventData objLeaveApplicationEventData = new LeaveApplicationEventData();
    //ShiftRoasterEventData objShiftRoaster = new ShiftRoasterEventData();
    //ShiftPatternEventData objShiftPattern = new ShiftPatternEventData();
    //RetrunNumberofDays obj_NumberofDays = new RetrunNumberofDays();
    //Hashtable hs_PatternId = new Hashtable();
    //DataSet ds_ShiftAllocdetails = new DataSet();
    DataSet ds = new DataSet();
    //DataSet ds_ShiftPattern = new DataSet();
    //string strEmployeeIds = "";
    //int[] months = new int[36];
    //Hashtable hs_year = new Hashtable(); 
    //Table tbl = new Table();
    string strAlert = string.Empty;
    #endregion
    #region Page Load Events
    protected override void Page_Load(object sender, EventArgs e)
    {
        // session checking
        base.Page_Load(sender, e);
        //get the culture info to set the language       
        string source_Language;
        source_Language = Convert.ToString(Session["Session_ActiveLanguage"]);
        rm = new ResourceManager(source_Language, System.Reflection.Assembly.Load("App_GlobalResources"));
        ci = Thread.CurrentThread.CurrentCulture;
        site.SiteMapProvider = Convert.ToString(Session["SiteMapProvider"]);
        LoadStrings(ci);
        string strSetAlert = "";
        strSetAlert = strSetAlert + "<script language='javascript'>";
        strSetAlert = strSetAlert + "SetAlertMessages('" + rm.GetString("Alert_SelectSheduleFrom", ci) + "','" + rm.GetString("Alert_SelectSheduleTo", ci) + "','" + rm.GetString("Alert_Are_you_sure_to_Save", ci) + "','" + rm.GetString("Alert_ClickAddButton", ci) + "','" + rm.GetString("Alert_EntertheEmployeeID", ci) + "');";
        strSetAlert = strSetAlert + "</script>";
        Page.RegisterStartupScript("SetAlertMessages", strSetAlert);
        Hidden1.Value = Convert.ToString(Session["IDateFormat"]);
        lblError.Text = "";
        gintUserId = Int32.Parse(Session["EmpAutoID"].ToString());
        if (Convert.ToString(Session["ISSingleorMultiple"]) == "IsMultiple")
        {
            rbtnMultiple.Checked = true;
            rbtnSingle.Checked = false;
            Session["ISSingleorMultiple"] = "";
        }
        else if (Convert.ToString(Session["ISSingleorMultiple"]) == "IsSingle")
        {
            rbtnSingle.Checked = true;
            rbtnMultiple.Checked = false;
            Session["ISSingleorMultiple"] = "";
        }
        if (rbtnMultiple.Checked == true)
        {
            divMultiple.Style.Add("display", "block");
            divSingle.Style.Add("display", "none");
        }
        else
        {
            divMultiple.Style.Add("display", "none");
            divSingle.Style.Add("display", "block");
        }
        if (!IsPostBack)
        {
            objcls_Common.menu("ShiftTransaction", "28");
            if (Session["CheckRecordsAddInPopUP"] != null)
            {
                Session["CheckRecordsAddInPopUP"] = null;
            }
            else
            {
                objShiftAllocation.DeleteEmpShiftDetails(gintUserId);
                Session["EmpDetails"] = null;
            }
            Session["previousCompanyId"] = Session["currentSession"];
            fillEmployee();
        }
    }
    #endregion
    #region Button events
    protected void btn_Delete_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            if (grv_Employees.Rows.Count == 0)
            {
                strAlert = string.Empty;
                strAlert = "alert('" + rm.GetString("Msg_ClickAddButtontoselectEmployeestoDeleteAllocatedShift", ci) + "')";
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", strAlert, true);
                btn_Add.Focus();
                return;
            }
            else if (txt_StartDate.Text == "")
            {
                lblError.Text = rm.GetString("Alert_ScheduleFromcannotbeEmpty", ci);
                txt_StartDate.Focus();
                return;
            }
            else if (txt_ToDate.Text == "")
            {
                lblError.Text = rm.GetString("Msg_ScheduleTocannotbeEmpty", ci);
                txt_ToDate.Focus();
                return;
            }
            else if (txt_StartDate.Text.Length < 10)
            {
                lblError.Text = rm.GetString("Alert_InvalidScheduleFromDate", ci);
                txt_StartDate.Focus();
                return;
            }
            else if (txt_ToDate.Text.Length < 10)
            {
                lblError.Text = rm.GetString("Alert_InvalidScheduleToDate", ci);
                txt_ToDate.Focus();
                return;
            }
            string strFromDate = "", strToDate = "";
            gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
            strFromDate = objcls_Common.DateConvertion(gstrDateFormat, txt_StartDate.Text);
            strToDate = objcls_Common.DateConvertion(gstrDateFormat, txt_ToDate.Text);
            dtFromdate = Convert.ToDateTime(strFromDate);
            dtTodate = Convert.ToDateTime(strToDate);
            int Days = dtTodate.CompareTo(dtFromdate);
            if (Days < 0)
            {
                strAlert = string.Empty;
                strAlert = "alert('" + rm.GetString("Msg_ScheduleFromDateshouldbelesserthantheScheduleToDate", ci) + "')";
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", strAlert, true);
                txt_ToDate.Focus();
                return;
            }
            DataSet ds_Shift = objShiftAllocation.CheckLeaveAndPermissionWhileDeleteEmpShift(Convert.ToString(gintUserId), strFromDate, strToDate, "SD");
            if (ds_Shift.Tables.Count > 0)
            {
                if (ds_Shift.Tables[0].Rows.Count > 0)
                {
                    string strMessage = Convert.ToString(ds_Shift.Tables[0].Rows[0][0]);
                    if (strMessage != string.Empty)
                    {
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString(strMessage, ci) + "')", true);
                        txt_ToDate.Focus();
                        return;
                    }
                }
            }
            string ColumnNames = string.Empty;
            if (dtFromdate.Year == dtTodate.Year)
            {
                int FromMonth = dtFromdate.Month;
                int ToMonth = dtTodate.Month;
                int increment = FromMonth;
                while (increment <= ToMonth)
                {
                    //if from month and to month are the same.
                    if (FromMonth == ToMonth)
                    {
                        ColumnNames = string.Empty;
                        ColumnNames = ToGetColumnNames(dtFromdate.Day, dtTodate.Day);
                    }
                    //if increment month is the from month 
                    else if (increment == FromMonth)
                    {
                        ColumnNames = string.Empty;
                        ColumnNames = ToGetColumnNames(dtFromdate.Day, 31);
                    }
                    //if increment month is the end month 
                    else if (increment == ToMonth)
                    {
                        ColumnNames = string.Empty;
                        ColumnNames = ToGetColumnNames(1, dtTodate.Day);
                    }
                    //if increment month is in between
                    else
                    {
                        ColumnNames = string.Empty;
                        ColumnNames = ToGetColumnNames(1, 31);
                    }
                    objShiftAllocation.Update_ShiftAllocation(ColumnNames, dtTodate.Year, increment, Session["EmpAutoID"].ToString());
                    increment = increment + 1;
                }
            }
            //If start year and end year differs.
            else
            {
                int FromYear = dtFromdate.Year;
                int ToYear = dtTodate.Year;
                int increment_Year = FromYear;
                while (increment_Year <= ToYear)
                {
                    //If the increment year is the start year.
                    if (increment_Year == FromYear)
                    {
                        int increment_Month = dtFromdate.Month;
                        while (increment_Month <= 12)
                        {
                            //if increment month is the from month 
                            if (increment_Month == dtFromdate.Month)
                            {
                                ColumnNames = string.Empty;
                                ColumnNames = ToGetColumnNames(dtFromdate.Day, 31);
                            }
                            //if increment month is in between
                            else
                            {
                                ColumnNames = string.Empty;
                                ColumnNames = ToGetColumnNames(1, 31);
                            }
                            objShiftAllocation.Update_ShiftAllocation(ColumnNames, increment_Year, increment_Month, Session["EmpAutoID"].ToString());
                            increment_Month = increment_Month + 1;
                        }
                    }
                    //If the increment year is the end year.
                    else if (increment_Year == ToYear)
                    {
                        int increment_Month = 1;
                        while (increment_Month <= dtTodate.Month)
                        {
                            //if increment month is the end month 
                            if (increment_Month == dtTodate.Month)
                            {
                                ColumnNames = string.Empty;
                                ColumnNames = ToGetColumnNames(1, dtTodate.Day);
                            }
                            else
                            {
                                ColumnNames = string.Empty;
                                ColumnNames = ToGetColumnNames(1, 31);
                            }
                            objShiftAllocation.Update_ShiftAllocation(ColumnNames, increment_Year, increment_Month, Session["EmpAutoID"].ToString());
                            increment_Month = increment_Month + 1;
                        }
                    }
                    //If the increment year is in between.
                    else
                    {
                        int increment_Month = 1;
                        while (increment_Month <= 12)
                        {
                            ColumnNames = string.Empty;
                            ColumnNames = ToGetColumnNames(1, 31);
                            objShiftAllocation.Update_ShiftAllocation(ColumnNames, increment_Year, increment_Month, Session["EmpAutoID"].ToString());
                            increment_Month = increment_Month + 1;
                        }
                    }
                    increment_Year = increment_Year + 1;
                }
            }
            //Update Processed Data Flag
            objLeaveApplicationEventData.UpdateProcessedDataFlagWithOutEmployeeID(0, strFromDate, strToDate, 0);
            //objShiftAllocation.DeleteEmpShiftDetails(gintUserId);
            if (rbtnMultiple.Checked == true)
            {
                Session["ISSingleorMultiple"] = "IsMultiple";
            }
            else
            {
                Session["ISSingleorMultiple"] = "IsSingle";
            }
            strAlert = string.Empty;
            strAlert = "alert('" + rm.GetString("Alert_ShiftAllocationhasbeendeletedsuccessfully", ci) + "'); location.replace('TA_UI_Transaction_ShiftAllocationDelete.aspx');";
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", strAlert, true);
            txt_StartDate.Text = string.Empty;
            txt_ToDate.Text = string.Empty;            
        }
    }
    protected void btn_Cancel_Click(object sender, EventArgs e)
    {
        objShiftAllocation.DeleteEmpShiftDetails(gintUserId);
        Session["EmpDetails"] = null;
        Response.Redirect("TA_UI_Transaction_ShiftAllocation.aspx");
    }
    #endregion
    #region User Defined Functions
    /// <summary>
    /// To get the column names which is used in update statement
    /// </summary>
    /// <param name="Startdata">day to start loop</param>
    /// <param name="EndDate">day to end loop</param>
    /// <returns></returns>
    private string ToGetColumnNames(int StartDateForLoop, int EndDateForLopp)
    {
        int i = 0;
        string ColumnNames = string.Empty;
        for (i = StartDateForLoop; i <= EndDateForLopp; i++)
        {
            if (ColumnNames == string.Empty)
            {
                ColumnNames = "Day" + i + "Shift=0";
            }
            else
            {
                ColumnNames = ColumnNames + ",Day" + i + "Shift=0";
            }
        }
        return ColumnNames;
    }
    public void CheckStartDate(object s, ServerValidateEventArgs e)
    {
        if (txt_StartDate.Text != "")
        {
            if (txt_StartDate.Text.Length >= 10)
            {
                string strStartDate = "";
                gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
                strStartDate = objcls_Common.DateConvertion(gstrDateFormat, txt_StartDate.Text);
                DateTime dtCurrent = DateTime.Now;
                DateTime dtStartDate = DateTime.Parse(strStartDate);
                TimeSpan diff = dtCurrent.Subtract(dtStartDate);
                int day = diff.Days;
                if (day <= 0)
                    e.IsValid = true;
                else
                {
                    // strAlert = string.Empty;
                    // strAlert = "alert('" + rm.GetString("Validator_ShiftAllocation_ScheduleFrom", ci) + "')";
                    // ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", strAlert, true);
                    //// base.Message(rm.GetString("Validator_ShiftAllocation_ScheduleFrom", ci)); ;
                    // e.IsValid = false;
                }
            }
            else
            {
                e.IsValid = true;
            }
        }
        else
        {
            e.IsValid = true;
        }
    }
    public void CheckToDate(object s, ServerValidateEventArgs e)
    {
        if (txt_ToDate.Text != "")
        {
            if (txt_ToDate.Text.Length >= 10)
            {
                string strToDate = "";
                gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
                strToDate = objcls_Common.DateConvertion(gstrDateFormat, txt_ToDate.Text);
                DateTime dtCurrent = DateTime.Now;
                DateTime dtToDate = DateTime.Parse(strToDate);
                TimeSpan diff = dtCurrent.Subtract(dtToDate);
                int day = diff.Days;
                if (day <= 0)
                {
                    e.IsValid = true;
                }
                else
                {
                    // strAlert = string.Empty;
                    // strAlert = "alert('" + rm.GetString("Validator_ShiftAllocation_ScheduleTo", ci) + "')";
                    // ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", strAlert, true);
                    //// base.Message(rm.GetString("Validator_ShiftAllocation_ScheduleTo", ci)); ;
                    // e.IsValid = false;
                    // return;
                }
            }
            else
            {
                e.IsValid = true;
            }
        }
        else
        {
            e.IsValid = true;
        }
    }
    private void LoadStrings(CultureInfo ci)
    {
        lbl_Header.Text = rm.GetString("UserGroups_ShiftAllocationDelete", ci);
        lbl_ScheduleFrom.Text = rm.GetString("ShiftAllocation_ScheduleFrom", ci);
        lbl_ScheduleTo.Text = rm.GetString("ShiftAllocation_ScheduleTo", ci);
        lbl_SelectedEmployees.Text = rm.GetString("ShiftAllocation_SelectedEmployees", ci);
        lbl_IndicatesMandatoryFields.Text = rm.GetString("IndicatesMandatoryFields", ci);
        CustomValidator1.ErrorMessage = rm.GetString("Validator_ShiftAllocation_ScheduleFrom", ci);
        CustomValidator3.ErrorMessage = rm.GetString("Validator_ShiftAllocation_ScheduleTo", ci);
        btn_Add.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Add", ci);
        btn_Delete.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Delete", ci);
        btn_Cancel.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Back", ci);
        lblDataView.Text = rm.GetString("lblDataView", ci);
        btn_ShiftAllocationView.Text = "&nbsp;&nbsp;" + rm.GetString("btn_ShiftAllocationView", ci);
        grv_Employees.Columns[2].HeaderText = rm.GetString("email_EmployeeId", ci);
        grv_Employees.Columns[3].HeaderText = rm.GetString("email_EmployeeName", ci);
        lblLoading.Text = rm.GetString("ProgressBarText", ci);
        lblSelectEmployee.Text = rm.GetString("Shift_SelectEmployee", ci);
        lblAllocationType.Text = rm.GetString("lbl_EmpSelectMode", ci);
        rbtnSingle.Text = rm.GetString("rbtn_EmployeeMaster_Single", ci);
        rbtnMultiple.Text = rm.GetString("rpt_Multiple", ci);
        lblEmployeeCode.Text = rm.GetString("email_EmployeeId", ci);
    }
    protected void grv_Employees_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        Label lblEmpAutoId = (Label)grv_Employees.Rows[e.RowIndex].FindControl("lbl_EmpAutoId");
        Label lblLoginEmployeeId = (Label)grv_Employees.Rows[e.RowIndex].FindControl("lbl_LoginEmployeeId");
        objShiftAllocation.DeleteEmpDetails(Convert.ToInt32(lblEmpAutoId.Text), Convert.ToInt32(lblLoginEmployeeId.Text));
        fillEmployee();
    }
    protected void grv_Employees_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            LinkButton lbDelete = new LinkButton();
            lbDelete = (LinkButton)e.Row.Cells[0].Controls[0];
            e.Row.Cells[0].BorderColor = System.Drawing.Color.White;
            if (lbDelete.Text == "Delete")
            {
                lbDelete.Text = rm.GetString("btn_Delete", ci);
            }
        }
        if (e.Row.RowType == DataControlRowType.Header)
        {
            e.Row.Cells[0].BorderColor = System.Drawing.Color.White;
        }
    }
    /// <summary>
    /// On page index changing, to load employee in the grid
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void grv_Employees_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grv_Employees.PageIndex = e.NewPageIndex;
        fillEmployee();
    }
    private void fillEmployee()
    {
        Session["previousCompanyId"] = Session["currentSession"];
        ds = objShiftAllocation.SelectEmployeeDetails(gintUserId);
        if (ds != null && ds.Tables[0].Rows.Count > 0)
        {
            grv_Employees.DataSource = ds;
            grv_Employees.DataBind();
        }
        else
        {
            grv_Employees.DataSource = ds;
            grv_Employees.DataBind();
        }
    }
    #endregion
    #region Not used
    /// <summary>
    /// Shifts not allocated employee details.
    /// </summary>
    /// <param name="empId">The emp id.</param>
    /// <param name="employeeName">Name of the employee.</param>
    /// <param name="dates">The dates.</param>
    /// <param name="notMonth">The not month.</param>
    /// <param name="notYear">The not year.</param>
    //private void ShiftNotAllocatedEmployeeDetails(string empId, string employeeName, string dates, string notMonth, string notYear)
    //{
    //    for (int i = Convert.ToInt16(notMonth); i <= Convert.ToInt16(notMonth); i++)
    //    {
    //        Label lblDates = new Label();
    //        lblDates.ID = "lblDates" + i.ToString() + empId;
    //        lblDates.Text = dates;
    //        Label lblMonth = new Label();
    //        lblMonth.ID = "lblMonth" + i.ToString() + empId;
    //        lblMonth.Text = notMonth;
    //        Label lblYear = new Label();
    //        lblYear.ID = "lblYear" + i.ToString() + empId;
    //        lblYear.Text = notYear;
    //        Label lblEmpId = new Label();
    //        lblEmpId.ID = "lblEmpId" + i.ToString() + empId;
    //        lblEmpId.Text = employeeName; 
    //        tbl.Width = Unit.Pixel(200);
    //        tbl.CssClass = "td";
    //        TableHeaderRow hr = new TableHeaderRow();
    //        TableHeaderCell hcDates = new TableHeaderCell();
    //        hcDates.Text = "Dates";
    //        hr.Cells.Add(hcDates);
    //        TableHeaderCell hcMonth = new TableHeaderCell();
    //        hcMonth.Text = "Month";
    //        hr.Cells.Add(hcMonth);
    //        TableHeaderCell hcYear = new TableHeaderCell();
    //        hcYear.Text = "Year";
    //        hr.Cells.Add(hcYear);
    //        TableHeaderCell hcEmpId = new TableHeaderCell();
    //        hcEmpId.Text = "Employee Name";
    //        hr.Cells.Add(hcEmpId);
    //        tbl.Rows.Add(hr);
    //        TableRow tr = new TableRow();
    //        TableCell tcDates = new TableCell();
    //        tcDates.Controls.Add(lblDates);
    //        tr.Cells.Add(tcDates);
    //        TableCell tcMonth = new TableCell();
    //        tcMonth.Controls.Add(lblMonth);
    //        tr.Cells.Add(tcMonth);
    //        TableCell tcYear = new TableCell();
    //        tcYear.Controls.Add(lblYear);
    //        tr.Cells.Add(tcYear);
    //        TableCell tcEmpId = new TableCell();
    //        tcEmpId.Controls.Add(lblEmpId);
    //        tr.Cells.Add(tcEmpId);
    //        tbl.Rows.Add(tr);
    //    }
    //}
    /// <summary>
    /// Fetech Employee Details
    /// </summary>
    /// <returns></returns>
    //private DataSet GetEmployeeDetails()
    //{
    //    DataSet ds_Employee = new DataSet();
    //    try
    //    {            
    //        ds_Employee = objShiftAllocation.SelectEmployeeDetails(gintUserId);
    //    }
    //    catch
    //    {
    //        //
    //    }
    //    return ds_Employee;
    //}
    #endregion
}
