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.Globalization;
using System.Threading;
using System.Reflection;
using System.Resources;
using System.IO;
using System.Text;
public partial class Transactions_TA_UI_Transaction_DataReprocessing : Base.BasePage
{
    #region VariableDeclaration
    ResourceManager rm;
    CultureInfo ci;
    ShiftRoasterEventData objShiftRoaster = new ShiftRoasterEventData();
    ShiftAllocationEvendata objShiftAllocation = new ShiftAllocationEvendata();
    cls_Common objcls_Common = new cls_Common();
    ShiftPatternEventData objShiftPatternOverLap = new ShiftPatternEventData();
    DataSet dsOverLapping = new DataSet();
    DataSet ds_Empdetails = new DataSet();
    DataSet ds_ShiftAllocdetails = new DataSet();
    DataSet ds = new DataSet();
    DataSet ds_ShiftPattern = new DataSet();
    DataTable dtEmpDetails = new DataTable();
    DataTable dtMonthYear = new DataTable();
    StringBuilder strOverLappedEmployeeIds = new StringBuilder();
    int gintUserId;
    string gstrIsValid = "T";
    string gstrDateFormat;
    string gstrUserGroupName = string.Empty;
    bool chkShiftAllocationExists;
    string strToDate = string.Empty;
    string strStartDate = string.Empty;
    int gintCompanyId;
    bool IsUnOverlappedEmployeeExists = false;
    string strAlert = string.Empty;
    int PatternDaysCount = 0;
    cls_Common objClassCommon = new cls_Common();
    DataSet dsYear = new DataSet();
    string strYearStartDate = string.Empty;
    string strYearEndDate = string.Empty;
    #endregion
    #region PageLoad
    protected override void Page_Load(object sender, EventArgs e)
    {
        // session checking
        base.Page_Load(sender, e);
        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);
        gintUserId = Int32.Parse(Session["EmpAutoID"].ToString());
        Hidden1.Value = Convert.ToString(Session["IDateFormat"]);
        dsYear = objClassCommon.GetYearsetting();
        if (dsYear.Tables[0].Rows.Count > 0)
        {
            strYearStartDate = (DateTime.Parse(dsYear.Tables[0].Rows[0]["FromDate"].ToString())).ToString(Session["MDateFormat"].ToString());
            strYearEndDate = (DateTime.Parse(dsYear.Tables[0].Rows[0]["ToDate"].ToString())).ToString(Session["MDateFormat"].ToString());
            dsYear.Dispose();
        }
        if (!Page.IsPostBack)
        {
            base.CheckPages(203);
            objcls_Common.menu("ShiftTransaction", "203");
            if (Session["CheckRecordsAddInPopUP"] != null)
            {
                Session["CheckRecordsAddInPopUP"] = null;
            }
            else
            {
                objShiftAllocation.DeleteEmpShiftDetails(gintUserId);
                Session["EmpDetails"] = null;
                Session["currentSession"] = null;
            }
            fillEmployee();
            if (Session["currentSession"] != null && Session["currentSession"].ToString() != string.Empty)
            {
                org_levelsEventData getOrg = new org_levelsEventData();
                getOrg.GetOrgParentLevels_FromID(Convert.ToInt32(Session["currentSession"]));
                DataSet ds_getOrg = new DataSet();
                ds_getOrg = getOrg.GetOrgParentLevels();
                if (ds_getOrg != null)
                {
                    if (ds_getOrg.Tables[0].Rows.Count > 0)
                    {
                        int companyId = Convert.ToInt32(ds_getOrg.Tables[0].Rows[0]["LevelID"].ToString());
                        gintCompanyId = companyId;
                    }
                }
            }
        }
        if (Session["UserGroupName"] != null)
        {
            gstrUserGroupName = Convert.ToString(Session["UserGroupName"]);
        }
    }
    #endregion
    #region User Procedures
    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();
        }
    }
    /// <summary>
    /// To validate start data and To restrict users other than super admin or 
    /// user having special rights to allocate shift for back date
    /// </summary>
    /// <param name="s"></param>
    /// <param name="e"></param>
    public void CheckStartDate(object s, ServerValidateEventArgs e)
    {
        if (gstrUserGroupName == "SuperAdmin" || Convert.ToString(Session["HasSpecialRights"]) == "True")
        {
            e.IsValid = true;
        }
        else
        {
            if (txt_StartDate.Text != string.Empty)
            {
                if (txt_StartDate.Text.Length >= 10)
                {
                    string strStartDate = string.Empty;
                    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;
                    // day = 0;
                    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;
            }
        }
    }
    /// <summary>
    /// To validate end data and To restrict users other than super admin or 
    /// user having special rights to allocate shift for back date
    /// </summary>
    /// <param name="s"></param>
    /// <param name="e"></param>
    public void CheckToDate(object s, ServerValidateEventArgs e)
    {
        if (gstrUserGroupName == "SuperAdmin" || Convert.ToString(Session["HasSpecialRights"]) == "True")
        {
            e.IsValid = true;
        }
        else
        {
            if (txt_ToDate.Text != string.Empty)
            {
                if (txt_ToDate.Text.Length >= 10)
                {
                    string strToDate = string.Empty;
                    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;
                    //day = 0;
                    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;
                    }
                }
                else
                {
                    e.IsValid = true;
                }
            }
            else
            {
                e.IsValid = true;
            }
        }
    }
    /// <summary>
    /// Shift allocation based on the pattern
    /// Inserts and update the shift details in the shift allocation table.
    /// Reprocesses the datas for the duration selected from processed data,clockdetails,raw data and manual time entry
    /// </summary>
    /// <param name="pattern"></param>
    /// <param name="dtmStartDate"></param>
    /// <param name="dtmToDate"></param>
    /// <param name="intStartDay"></param>
    /// <param name="PatternDaysCount"></param>
    private void ShiftAllocation(DateTime dtmStartDate, DateTime dtmToDate)
    {
        try
        {
            objShiftAllocation.ShiftAllocationReprocess_ProcessedData(dtmStartDate, dtmToDate, Session["EmpAutoID"].ToString());
            objShiftAllocation.ShiftAllocationReprocess_ClockDetails(dtmStartDate, dtmToDate, Session["EmpAutoID"].ToString());
            objShiftAllocation.ShiftAllocationReprocess_ManualEntry(dtmStartDate, dtmToDate, Session["EmpAutoID"].ToString());
            objShiftAllocation.ShiftAllocationReprocess_RawData(dtmStartDate, dtmToDate, Session["EmpAutoID"].ToString());
        }
        catch (Exception ex)
        {
            Response.Write(ex.ToString());
        }
        objShiftAllocation.DeleteEmpShiftDetails(gintUserId);
        Session["EmpDetails"] = null;
    }
    /// <summary>
    /// Getting Information from resource file and display it in label
    /// </summary>
    /// <param name="ci"></param>
    private void LoadStrings(CultureInfo ci)
    {
        lbl_Header.Text = rm.GetString("DataReprocessing", 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_Save.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Save", ci);
        lblLoading.Text = rm.GetString("ProgressBarText", ci);
        btn_Cancel.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Back", ci);
        grv_Employees.Columns[2].HeaderText = rm.GetString("email_EmployeeId", ci);
        grv_Employees.Columns[3].HeaderText = rm.GetString("email_EmployeeName", ci);
        lblSelectEmployee.Text = rm.GetString("lblSelectEmployee", ci);
    }
    #endregion
    #region button events
    /// <summary>
    /// To validate and save the shift allocation details
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btn_Save_Click(object sender, EventArgs e)
    {        
        if (grv_Employees.Rows.Count == 0)
        {
            lblError.Text = rm.GetString("Alert_ClickAddButtontoselectEmployeesforShiftAllocation", ci);
            btn_Add.Focus();
            return;
        }
        else if (txt_StartDate.Text == "")
        {
            lblError.Text = rm.GetString("Alert_ScheduleFromcannotbeEmpty", ci);
            return;
        }
        else if (txt_ToDate.Text == "")
        {
            lblError.Text = rm.GetString("Alert_ScheduleFromcannotbeEmpty", ci);
            return;
        }
        else if (txt_StartDate.Text.Length < 10)
        {
            lblError.Text = rm.GetString("Alert_InvalidScheduleFromDate", ci);
            return;
        }
        else if (txt_ToDate.Text.Length < 10)
        {
            lblError.Text = rm.GetString("Alert_InvalidScheduleToDate", ci);
            return;
        }
        gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
        strStartDate = objcls_Common.DateConvertion(gstrDateFormat, txt_StartDate.Text);
        strToDate = objcls_Common.DateConvertion(gstrDateFormat, txt_ToDate.Text);
        DateTime dtmStartDate = DateTime.Parse(strStartDate);
        DateTime dtmToDate = DateTime.Parse(strToDate);
        int Days = dtmToDate.CompareTo(dtmStartDate);
        if (Days < 0)
        {
            strAlert = string.Empty;
            strAlert = "alert('" + rm.GetString("Msg_ScheduleFromDateshouldbelesserthantheScheduleToDate", ci) + "')";
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", strAlert, true);
            return;
        }
        ds = objShiftAllocation.SelectEmployeeDetails(gintUserId);
        dtEmpDetails = ds.Tables[0];
        ShiftAllocation(dtmStartDate, dtmToDate);
        string strScript = "<script language='javascript' type='text/javascript'>";
        strScript += "alert('" + rm.GetString("Alert_DataReprocessingsavedSuccessfully", ci) + "');location.replace('TA_UI_Transaction_DataReprocessing.aspx');";
        strScript += " </script>";
        ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", strScript, false);
        txt_StartDate.Text = string.Empty;
        txt_ToDate.Text = string.Empty;
    }
    /// <summary>
    /// Cancel shift allocation
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btn_Cancel_Click(object sender, EventArgs e)
    {
        objShiftAllocation.DeleteEmpShiftDetails(gintUserId);
        Session["EmpDetails"] = null;
        Response.Redirect("TA_UI_Transaction_ShiftAllocation.aspx");
    }
    #endregion
    #region gridview events
    /// <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();
    }
    /// <summary>
    /// To delete the employee from the grid.
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    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();
    }
    /// <summary>
    /// To change the name of the link button(delete) based on the language.
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    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;
        }
    }
    #endregion
}
