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;
/*************************************************************************************************
* 	Project Name    	 	    :    TimeCheck                       Started  	: 10-01-2009
*	Module          	 	    :    OverTime Sanction                         		
*	Description		 	        :    OverTime Sanction Filter
*	Programmer	 	            :    Sasireka.M
*   Modified by 		 	    :    Sasireka.M
*	Modified Date and Reason    :    16.05.09 Updated Coding based on the Coding Standards                                                      
**************************************************************************************************/
public partial class Transactions_TA_UI_Transactions_OverTimeSanction : Base.BasePage
{
    #region Variables
    /// <summary>
    /// To get the common functions
    /// </summary>
    /// 
    FileStream aFile;
    cls_Common objCommon = new cls_Common();
    OTEventData objOT = new OTEventData();
    YearSettingsEventData objYearSettingsEventData = new YearSettingsEventData();
    /// <summary>
    /// To get the Employee related details
    /// </summary>
    EmployeeEventData objEmployee = new EmployeeEventData();
    /// <summary>
    /// To get the users rights
    /// </summary>
    Cls_CheckUser objCheckUser = new Cls_CheckUser();
    /// <summary>
    /// Instance of the ReportCommon function
    /// </summary>
    Rpt_Common rptcommon = new Rpt_Common();
    /// <summary>
    /// Instance of the Resource Manager
    /// </summary>
    ResourceManager objrm;
    /// <summary>
    /// Instance of the CultureInfo
    /// </summary>
    CultureInfo objci;
    /// <summary>
    /// String type Variable
    /// </summary>
    string strFromdate, gstrDateFormat, strTodate;
    /// <summary>
    /// Individual Type users count
    /// </summary>
    int intIndividualUser = 0;
    #endregion
    #region PageLoadEvent
    /// <summary>
    /// Handles the Load event of the Page control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected override void Page_Load(object sender, EventArgs e)
    {
        base.Page_Load(sender, e);
        string strSourceLanguage;
        //Getting resource file information
        strSourceLanguage = Convert.ToString(Session["Session_ActiveLanguage"]);
        objrm = new ResourceManager(strSourceLanguage, System.Reflection.Assembly.Load("App_GlobalResources"));
        objci = Thread.CurrentThread.CurrentCulture;
        site.SiteMapProvider = Convert.ToString(Session["SiteMapProvider"]);
        //Get the label information from resource file
        LoadStrings(objci);
        if (!Page.IsPostBack)
        {
            base.CheckPages(0);
        }
        Hidden1.Value = Convert.ToString(Session["IDateFormat"]);
        if (!IsPostBack)
        {
            BindingEmployeeCategoryandType();
            objCommon.menu("OverTime", "97");
        }
        grvImportDetails.Styles.CssFilePath = Convert.ToString(Session["GridCSS"]);
        //check the User Rights
        UserRights();
        string strSetAlert = "";
        strSetAlert = strSetAlert + "<script language='javascript'>";
        strSetAlert = strSetAlert + "MaxLengthh('" + objrm.GetString("Alert_MaximumLengthis", objci) + "');";
        strSetAlert = strSetAlert + "SetAlertMessages('" + objrm.GetString("Alert_PleaseselectFromDate", objci) + "','" + objrm.GetString("Alert_PleaseselectToDate", objci) + "','" + objrm.GetString("Alert_SelectStatus", objci) + "','" + objrm.GetString("Msg_GrearterThanFrmDate", objci) + "');";
        strSetAlert = strSetAlert + "SetAlertCheckDate('" + objrm.GetString("Alert_Validdatemonthfourdigit", objci) + "','" + objrm.GetString("Alert_Invalidyearentry", objci) + "','" + objrm.GetString("Alert_Invalidmonthentry", objci) + "','" + objrm.GetString("Alert_Invaliddateentry", objci) + "','" + objrm.GetString("Alert_IncorrectdateformatDDMONYYYY", objci) + "','" + objrm.GetString("Alert_Entertime", objci) + "','" + objrm.GetString("Alert_Invalidvalueforhours", objci) + "','" + objrm.GetString("Alert_Invalidvalueforminites", objci) + "','" + objrm.GetString("Alert_Invalidtimeformat1", objci) + "','" + objrm.GetString("Alert_PleaseentervalidDateandTime", objci) + "','" + objrm.GetString("Alert_ValiddatemonthMMDDYYHHMM", objci) + "','" + objrm.GetString("Alert_ValiddatemonthMMDDYYHHMMTT", objci) + "','" + objrm.GetString("Alert_PleaseentervalidDateandTime", objci) + "','" + objrm.GetString("Alert_Invalidvalueforhours", objci) + "','" + objrm.GetString("Alert_Invalidvalueforminites", objci) + "');";
        strSetAlert = strSetAlert + "</script>";
        Page.RegisterStartupScript("SetAlertMessages", strSetAlert);

        if (Convert.ToString(Session["UserGroupName"]) == "SuperAdmin" || Convert.ToString(Session["IndividualUsers"]) != "True")
        {
            import1.Style.Add("display", "");
            import2.Style.Add("display", "");
            import3.Style.Add("display", "");
            import4.Style.Add("display", "");
            //import1.Style.Add("display", "none");
            //import2.Style.Add("display", "none");
            //import3.Style.Add("display", "none");
            //import4.Style.Add("display", "none");
        }
        else
        {
            import1.Style.Add("display", "none");
            import2.Style.Add("display", "none");
            import3.Style.Add("display", "none");
            import4.Style.Add("display", "none");
        }
    }
    #endregion
    #region UserDefinedFunctions
    #region LoadStrings
    /// <summary>
    /// Loads the strings.
    /// </summary>
    /// <param name="ci">The ci.</param>
    private void LoadStrings(CultureInfo ci)
    {
        btnView.Text = "&nbsp;&nbsp;" + objrm.GetString("btn_View", ci);
        lblEmployeeName.Text = objrm.GetString("email_EmployeeName", ci);
        lblEmployeeId.Text = objrm.GetString("email_EmployeeId", ci);
        lblEmpCategory.Text = objrm.GetString("Master_Category", ci);
        lblEmpType.Text = objrm.GetString("Master_Type", ci);
        //lblTimePeriod.Text = objResourceManager.GetString("Reports_TimePeriod", ci);
        lblFrom.Text = objrm.GetString("email_FromDate", ci);
        lblTo.Text = objrm.GetString("email_ToDate", ci);
        lblStatus.Text = objrm.GetString("email_Status", ci);
        lblOverTimeSanction.Text = objrm.GetString("Transaction_OverTime_Sanction", ci);
        lblEmpSwipe.Text = objrm.GetString("TerminalDataType_Card_No", ci);
        ddlOTStatus.Items[0].Text = objrm.GetString("ExportData_All", ci);
        ddlOTStatus.Items[1].Text = objrm.GetString("btn_Approved", ci);
        ddlOTStatus.Items[2].Text = objrm.GetString("btn_Forwarded", ci);
        ddlOTStatus.Items[3].Text = objrm.GetString("btn_Pending", ci);
        ddlOTStatus.Items[4].Text = objrm.GetString("btn_Reject", ci);
        cvrFromDate.ErrorMessage = objrm.GetString("Alert_SelectvalidFromDate", ci);
        cvrToDate.ErrorMessage = objrm.GetString("Alert_SelectvalidToDate", ci);
        cvrComToDate.ErrorMessage = objrm.GetString("Msg_SelectvaliddatecomparewithFromdate", ci);
        rfvFromDate.ErrorMessage = objrm.GetString("Alert_PleaseselectFromDate", ci);
        rfvToDate.ErrorMessage = objrm.GetString("Alert_PleaseselectToDate", ci);
        ddlEmpCatagory.Items[0].Text = objrm.GetString("Select", ci);
        ddlEmpType.Items[0].Text = objrm.GetString("Select", ci);
        lbl_IndicatesMandatoryFields.Text = objrm.GetString("IndicatesMandatoryFields", ci);
        lblSanctionType.Text = objrm.GetString("Caption_SanctionType", ci);
        rbtnOverTime.Text = objrm.GetString("Menu_Reports_OverTime", ci);
        rbtnCompoff.Text = objrm.GetString("Caption_CompOff", ci);
        rbtnOTCompOff.Text = objrm.GetString("rbtn_OTCompOff", ci);
        lblFilter.Text = objrm.GetString("lblFilter", ci);
        lbl_OT_Comp.Text = objrm.GetString("Transaction_OverTime_Sanction", ci);
    }
    #endregion
    #region LeaveStatus
    /// <summary>
    /// Loads the leave status.
    /// </summary>
    public void LoadLeaveStatus()
    {
        ddlOTStatus.Items.Clear();
        ddlOTStatus.Items.Insert(0, "All");
        ddlOTStatus.Items.Insert(1, "Pending");
        ddlOTStatus.Items.Insert(2, "Approved");
        ddlOTStatus.Items.Insert(3, "Forwarded");
        ddlOTStatus.Items.Insert(4, "Rejected");
    }
    #endregion
    #region validateFromdate
    /// <summary>
    /// Validates from date.
    /// </summary>
    /// <param name="s">The s.</param>
    /// <param name="e">The <see cref="System.Web.UI.WebControls.ServerValidateEventArgs"/> instance containing the event data.</param>
    public void ValidateFromDate(object s, ServerValidateEventArgs e)
    {
        try
        {
            strFromdate = txtFromDate.Text;
            gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
            //Convert current datetime to default datetime format
            strFromdate = objCommon.DateConvertion(gstrDateFormat, strFromdate);
            DateTime dtCurrentDate = Convert.ToDateTime(DateTime.Today.Date);
            DateTime dtFromDate = DateTime.Parse(strFromdate);
            TimeSpan DateTimeDiff = dtFromDate.Subtract(dtCurrentDate);
            int intDay = DateTimeDiff.Days;
            if (intDay <= 0)
                e.IsValid = true;
            else
                e.IsValid = false;
        }
        catch (Exception ex)
        {
            Message(ex.ToString());
        }
    }
    #endregion
    #region ValidateToDate
    /// <summary>
    /// Validate the ToDate
    /// </summary>
    /// <param name="s"></param>
    /// <param name="e"></param>
    public void ValidateToDate(object s, ServerValidateEventArgs e)
    {
        try
        {
            gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
            strTodate = txtToDate.Text;
            //Convert current datetime to default datetime format
            strTodate = objCommon.DateConvertion(gstrDateFormat, strTodate);
            DateTime dtCurrentDate = Convert.ToDateTime(DateTime.Today.Date);
            DateTime dtFromDate = DateTime.Parse(strTodate);
            TimeSpan DateTimeDiff = dtFromDate.Subtract(dtCurrentDate);
            int intDay = DateTimeDiff.Days;
            if (intDay <= 0)
                e.IsValid = true;
            else
                e.IsValid = false;
        }
        catch (Exception ex)
        {
            Message(ex.ToString());
        }
    }
    #endregion
    #region CompareDate
    /// <summary>
    /// Compare ToDate with FromDate
    /// </summary>
    /// <param name="s"></param>
    /// <param name="e"></param>
    public void CompareDate(object s, ServerValidateEventArgs e)
    {
        try
        {
            strFromdate = txtFromDate.Text;
            strTodate = txtToDate.Text;
            gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
            //Convert current datetime to default datetime format
            strTodate = objCommon.DateConvertion(gstrDateFormat, strTodate);
            strFromdate = objCommon.DateConvertion(gstrDateFormat, strFromdate);
            DateTime dtToDate = DateTime.Parse(strTodate);
            DateTime dtFromDate = DateTime.Parse(strFromdate);
            TimeSpan DateTimeDiff = dtToDate.Subtract(dtFromDate);
            int intDay = DateTimeDiff.Days;
            if (intDay >= 0)
                e.IsValid = true;
            else
                e.IsValid = false;
        }
        catch (Exception ex)
        {
            Message(ex.ToString());
        }
    }
    #endregion
    #region "EmployeeCategoryandType
    /// <summary>
    /// Bindings the type of the employee category and Type.
    /// </summary>
    private void BindingEmployeeCategoryandType()
    {
        // employee category binding
        DataSet dsCategory = new DataSet();
        try
        {
            //Get the Employee Category details
            dsCategory = objEmployee.SelectCategoryDetailsEmployee("");
            if (dsCategory != null)
            {
                if (dsCategory.Tables[0].Rows.Count > 0)
                {
                    ddlEmpCatagory.DataSource = dsCategory;
                    ddlEmpCatagory.DataTextField = "CategoryName";
                    ddlEmpCatagory.DataValueField = "CategoryId";
                    ddlEmpCatagory.DataBind();
                }
                dsCategory.Dispose();
                foreach (ListItem item in ddlEmpCatagory.Items)
                {
                    item.Attributes.Add("title", item.Text);
                }
            }
        }
        catch (Exception ex)
        {
            Message(ex.ToString());
        }
        // employee type binding
        DataSet dsType = new DataSet();
        try
        {
            //Get the Employee Type Details
            dsType = objEmployee.SelectTypeDetailsEmployee("");
            if (dsType != null)
            {
                if (dsType.Tables[0].Rows.Count > 0)
                {
                    ddlEmpType.DataSource = dsType;
                    ddlEmpType.DataTextField = "TypeName";
                    ddlEmpType.DataValueField = "TypeId";
                    ddlEmpType.DataBind();
                }
                dsType.Dispose();
                foreach (ListItem item in ddlEmpType.Items)
                {
                    item.Attributes.Add("title", item.Text);
                }
            }
        }
        catch (Exception ex)
        {
            Message(ex.ToString());
        }
    }
    #endregion
    /// <summary>
    /// To check rights for the logged in user
    /// </summary>
    private void UserRights()
    {
        DataSet ds_Checkuser = new DataSet();
        if (ViewState["vs_ds_Checkuser"] != null)
            ds_Checkuser = (DataSet)ViewState["vs_ds_Checkuser"];
        else
        {
            ds_Checkuser = objCheckUser.checkRights(97, Convert.ToInt32(Session["userGroup_Id"]), "viewPrv");
            ViewState["vs_ds_Checkuser"] = ds_Checkuser;
        }
        if (ds_Checkuser.Tables[0].Rows.Count == 0)
            Response.Redirect("TransactionLandingPage.aspx");
    }
    #endregion

    protected void lnkbtnExport_Click(object sender, EventArgs e)
    {
        OTEmployeeDetails();
    }

    protected void OTEmployeeDetails()
    {
        DataSet dsYearSetting = new DataSet();
        DataSet dsOtEmployee = new DataSet();
        string strFromdate, strTodate;
        dsYearSetting = objYearSettingsEventData.GetActiveYearSettings();
        if (dsYearSetting.Tables[0].Rows.Count <= 0)
            return;
        else
        {
            strFromdate = Convert.ToString(dsYearSetting.Tables[0].Rows[0]["FromDate"]);
            strTodate = Convert.ToString(dsYearSetting.Tables[0].Rows[0]["ToDate"]);
        }
        string EmployeeID = Convert.ToString(txtEmployeeId.Text);
        string EmployeeName = Convert.ToString(txtEmployeeName.Text);
        int EmployeeCategory = Convert.ToInt32(ddlEmpCatagory.SelectedItem.Value);
        int EmployeeType = Convert.ToInt32(ddlEmpCatagory.SelectedItem.Value);
        string gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
        string Fromdate = Convert.ToString(txtFromDate.Text);
        string Todate = Convert.ToString(txtToDate.Text);
        string SanctionType = Convert.ToString(rbtnOverTime.Checked);
        string strSwipeCard = Convert.ToString(txtSwipeCard.Text);
        string OTStatus = Convert.ToString(ddlOTStatus.SelectedItem.Value);
        if (Fromdate == string.Empty)
            Fromdate = strFromdate;
        else
            Fromdate = objCommon.DateConvertion(gstrDateFormat, Fromdate);
        if (Todate == string.Empty)
            Todate = strTodate;
        else
            Todate = objCommon.DateConvertion(gstrDateFormat, Todate);

        string Level = rptcommon.getNodes(Convert.ToInt32(Session["parentLevelId"]), Convert.ToString(Session["LevelRights"]));
        dsOtEmployee = objOT.SelectOverTimeEmployee(Convert.ToInt32(Session["EmpAutoID"]), Fromdate, Todate, EmployeeID, EmployeeName, Level, EmployeeCategory, EmployeeType, Convert.ToString(Session["UserGroupName"]), Convert.ToString(Session["GradeLevel"]), OTStatus, strSwipeCard, Convert.ToInt32(Session["parentLevelId"]), SanctionType);
        if (dsOtEmployee.Tables.Count > 0)
        {
            if (dsOtEmployee.Tables[0].Rows.Count > 0)
            {
                Session["Export_ExcelData"] = dsOtEmployee;
                Response.Redirect("~/Reports/Excel_Export.aspx?ReportName=OverTimeSanction&FrmDate=" + Convert.ToString(Fromdate) + "&toDate=" + Convert.ToString(Todate) + "");
            }
            else
                Message(objrm.GetString("Alert_Thereisnorecord", objci));
        }
        else
            Message(objrm.GetString("Alert_Thereisnorecord", objci));
    }
    private DataSet ImportOvertimeData(FileInfo fileInfo)
    {
        string strLine;
        string[] strArray;
        char[] charArray = new char[] { ',' };
        string[] strColumnName = { "Sl.no", "Employee_Code_Id", "Employee_FirstName", "LevelName", "date", "HrsOT", "ActHrsOT", "OffOT", "ActOffOT", "HolOT", "ActHolOT", "SPEC_NormOT1", "Modified_Spec_NormOTHrs1", "SPEC_NormOT2", "Modified_Spec_NormOTHrs2", "SPEC_OffOT1", "Modified_Spec_OffOTHrs1", "SPEC_OffOT2", "Modified_Spec_OffOTHrs2", "SPEC_HOLOT1", "Modified_Spec_HolOTHrs1", "SPEC_HOLOT2", "Modified_Spec_HolOTHrs2", "OverTimeStatus" };
        DataSet dsOvertime = new DataSet("dsOverTime");
        DataTable dtOvertime = dsOvertime.Tables.Add("dtOvertime");
        foreach (string str in strColumnName)
        {
            dtOvertime.Columns.Add(str);
        }
        aFile = new FileStream(fileInfo.FullName.ToString(), FileMode.Open);
        StreamReader sr = new StreamReader(aFile);
        strLine = sr.ReadLine();
        strArray = strLine.Split(charArray);
        if (strArray.Length != dtOvertime.Columns.Count)
        {
            string strScript = "";
            strScript = "<script language='javascript'>";
            strScript = strScript + "alert('" + objrm.GetString("Alert_ErrorinShiftImporting", objci) + "');";
            strScript = strScript + "</script>";
            Page.RegisterStartupScript("Alert", strScript);
            return null;
        }
        strLine = sr.ReadLine();
        strArray = null;
        while (strLine != null)
        {
            strArray = strLine.Split(charArray);
            dtOvertime.Rows.Add(strArray);
            strLine = sr.ReadLine();
        }
        StringWriter swOvertime = new StringWriter();
        dsOvertime.WriteXml(swOvertime);
        string strAlloc = Convert.ToString(swOvertime);
        aFile.Dispose();
        return objOT.UpdateOvertimeHours_Import(strAlloc, Convert.ToInt64(Session["EmpAutoID"]), Convert.ToString(Session["UserGroupName"]));
    }
    protected void btn_Upload_Click(object sender, EventArgs e)
    {
        try
        {
            if (fup_ShiftImport.HasFile)
            {
                string filename = fup_ShiftImport.FileName.Substring(fup_ShiftImport.FileName.LastIndexOf("\\") + 1);
                string fileType = System.IO.Path.GetExtension(filename);
                if (fileType == ".csv")
                {
                    string strFilePath = Server.MapPath("Uploads");
                    FileInfo fileInfo = new System.IO.FileInfo(strFilePath + "\\" + fup_ShiftImport.FileName);
                    fup_ShiftImport.SaveAs(strFilePath + "\\" + fup_ShiftImport.FileName);
                    if (fup_ShiftImport.PostedFile.ContentLength == fileInfo.Length)
                    {
                        if (fileType == ".csv")
                        {
                            DataSet dsInvalidData = ImportOvertimeData(fileInfo);
                            string strScript = "";
                            if (dsInvalidData.Tables.Count > 0)
                            {
                                if (dsInvalidData.Tables[0].Columns.Contains("Employee_Id"))
                                {
                                    grvImportDetails.DataSource = dsInvalidData;
                                    grvImportDetails.DataBind();
                                    strScript = "<script language='javascript'>";
                                    strScript = strScript + "alert('Overtime data is not imported Successfully. Invalid data found in excel sheet, please correct it first and then import the file.');";
                                    strScript = strScript + "</script>";
                                    Page.RegisterStartupScript("Alert", strScript);
                                }
                                else
                                {
                                    grvImportDetails.DataSource = null;
                                    grvImportDetails.DataBind();
                                    string strMsg = Convert.ToString(dsInvalidData.Tables[0].Rows[0]["Message"]);
                                    strScript = "<script language='javascript'>";
                                    strScript = strScript + "alert('" + (strMsg.Contains("Msg:") ? "Overtime data imported successfully" : "Overtime data not imported successfully") + "');";
                                    strScript = strScript + "</script>";
                                    Page.RegisterStartupScript("Alert", strScript);
                                }
                            }
                        }
                    }
                    else
                        commonAlertMessage(objrm.GetString("Alert_ErrorinImportingEmployee", objci));
                }
                else
                    commonAlertMessage(objrm.GetString("Alert_TheUploadedfileisnotExcelfile", objci));
            }
            else
                commonAlertMessage(objrm.GetString("Alert_Youhavenotspecifiedafile", objci));
        }
        catch (Exception Ex)
        {
            string strErr = Convert.ToString(Ex.Message);
            commonAlertMessage(strErr.Replace("\r", "").Replace("\n", ""));
        }
        finally
        {
            try
            {
                if (fup_ShiftImport.HasFile)
                {
                    string StrFilePath = Convert.ToString(Server.MapPath("Uploads")) + "\\" + fup_ShiftImport.FileName;
                    System.IO.File.Delete(StrFilePath);
                }
            }
            catch
            {
            }
        }
    }
    private void commonAlertMessage(string alertmsg)
    {
        Message(alertmsg);
    }

    protected void btnClear_Click(object sender, EventArgs e)
    {
        grvImportDetails.DataSource = null;
        grvImportDetails.DataBind();
    }
}
