using System;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Globalization;
using System.Threading;
using System.Resources;
using DevExpress.Web;
/****************************************************************************************************************************
* Project Name    : TimeCheck                  Started Date  : 18-July-2007
* Module          : Manual Time Entry           
* Programmer      :Kumthini.L
* Current Storage : \\Angler56\Projects\Inprogress\SCREEN1206\code\Time_AttendanceApp
* BackUp          : \\windev\Projects\Inprogress\SCREEN1206\code\Time_AttendanceApp
****************************************************************************************************************************/
public partial class Transactions_TA_UI_Transactions_ManualTimeEntry : Base.BasePage
{
    #region "Variable Declaration"
    ResourceManager rm;
    CultureInfo ci;
    // Create object for the Class ManualEntryEventData to use the methods that are used to interact with the Database
    ManualEntryEventData objManualTimeEntry = new ManualEntryEventData();
    cls_Common objClassCommon = new cls_Common();
    Cls_CheckUser objCheckUser = new Cls_CheckUser();
    DataSet ds_Checkuser = new DataSet(); string source_Language;
    #endregion
    #region PageLoad
    protected override void Page_Load(object sender, EventArgs e)
    {
        // session checking
        base.Page_Load(sender, e);
        GridView1.Styles.CssFilePath = Convert.ToString(Session["GridCSS"]);
        //get the culture info to set the 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"]);
        Session["parentLevelId"] = "0";
        // If Page not PostBack, then focus the Add Button
        if (!IsPostBack)
        {            
            base.CheckPages(26);            
            objClassCommon.menu("ManualTransaction", "26");
            //Set UserRights
            Userrights();
            LoadStrings(ci);
            BindControlsBasedOnLicense();
            string strSetAlert = "";
            strSetAlert = strSetAlert + "<script language='javascript'>";
            strSetAlert = strSetAlert + "MaxLengthh('" + rm.GetString("Alert_MaximumLengthis", ci) + "');";
            strSetAlert = strSetAlert + "SetAlertMessages('" + rm.GetString("Alert_Holiday_SelectHolidayType", ci) + "','" + rm.GetString("Alert_Fromdate", ci) + "','" + rm.GetString("Alert_ToDate", ci) + "','" + rm.GetString("Alert_Holiday_FillDescription", ci) + "','" + rm.GetString("Alert_EnterToDate", ci) + "','" + rm.GetString("Alert_ConfirmSave", ci) + "');";
            strSetAlert = strSetAlert + "SetAlertMessages('" + rm.GetString("Alert_FillDetails", ci) + "','" + rm.GetString("Alert_FillFromToDate", ci) + "');";
            strSetAlert = strSetAlert + "SetAlertCheckDate('" + rm.GetString("Alert_Validmonthdatefourdigit", ci) + "','" + rm.GetString("Alert_Validdatemonthfourdigit", ci) + "','" + rm.GetString("Alert_Invalidyearentry", ci) + "','" + rm.GetString("Alert_Invalidmonthentry", ci) + "','" + rm.GetString("Alert_Invaliddateentry", ci) + "','" + rm.GetString("Alert_IncorrectdateformatDDMONYYYY", ci) + "','" + rm.GetString("Alert_Entertime", ci) + "','" + rm.GetString("Alert_Invalidvalueforhours", ci) + "','" + rm.GetString("Alert_Invalidvalueforminites", ci) + "','" + rm.GetString("Alert_Invalidtimeformat1", ci) + "','" + rm.GetString("Alert_PleaseentervalidDateandTime", ci) + "','" + rm.GetString("Alert_ValiddatemonthMMDDYYHHMM", ci) + "','" + rm.GetString("Alert_ValiddatemonthMMDDYYHHMMTT", ci) + "','" + rm.GetString("Alert_PleaseentervalidDateandTime", ci) + "','" + rm.GetString("Alert_Invalidvalueforhours", ci) + "','" + rm.GetString("Alert_Invalidvalueforminites", ci) + "');";
            strSetAlert = strSetAlert + "</script>";
            Page.RegisterStartupScript("SetAlertMessages", strSetAlert);
            // Focus Add Button
            btn_Add.Focus();
        }
        Hidden1.Value = Convert.ToString(Session["IDateFormat"]);
        int intIndividualUser = objCheckUser.CheckIndividualUser(Convert.ToString(Session["UserGroupName"]));
        if (intIndividualUser >= 1)
        {
            trSwipeCardNo.Visible = false;
            trEmpName.Visible = false;
            //tdAdd.Visible = false;
        }

    }
    #endregion
    #region ButtonEvents
    // Add Button - Click Event
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        Response.Redirect("../Transactions/TA_UI_Transactions_ManualTimeEntryAdd.aspx");
    }
    protected void btn_Clear_Click(object sender, EventArgs e)
    {
        grid_RestoreDefault();
    }
    protected void btn_Search_Click(object sender, EventArgs e)
    {
        FillGrid_Search();
    }
    protected void btn_Cancel_Click(object sender, EventArgs e)
    {
        Response.Redirect("TA_UI_Transactions_ManualTimeEntryList.aspx");
    }
    #endregion
    #region UserDefinedFunctions
    private void BindControlsBasedOnLicense()
    {
        #region Eastman
        if (Convert.ToString(Session["packageID"]) != "")
            if (Convert.ToInt32(Session["packageID"]) >= 160) /*TimecheckV2.9_Enterprice*/
            {
                // for individual user it not be loaded. import option.
                if (Convert.ToString(Session["IndividualUsers"]) == "True")
                {
                    btnImport.Style.Add("display", "none");
                }
            }
        #endregion
    }
    //Getting Information from resource file and display it in label    
    private void LoadStrings(CultureInfo ci)
    {
        lbl_Header.Text = rm.GetString("UserGroups_ManualTimeEntry", ci);
        lbl_EmployeeName.Text = rm.GetString("email_EmployeeName", ci);
        lbl_EmployeeId.Text = rm.GetString("email_EmployeeId", ci);
        lblTimePeriod.Text = rm.GetString("ShiftExchange_DateRange", ci);
        lblStartDate.Text = rm.GetString("email_FromDate", ci);
        lblEndDate.Text = rm.GetString("email_ToDate", ci);
        btn_Search.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Search", ci);
        btn_Clear.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Clear", ci);
        btn_Add.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Add", ci);
        btn_Cancel.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Back", ci);
        GridView1.Columns[1].Caption = rm.GetString("email_EmployeeId", ci);
        GridView1.Columns[2].Caption = rm.GetString("email_EmployeeName", ci);
        GridView1.Columns[4].Caption = rm.GetString("ManualTimeEntry_InDate", ci);
        GridView1.Columns[5].Caption = rm.GetString("ManualTimeEntry_In_Time", ci);
        GridView1.Columns[3].Caption = rm.GetString("ManualTimeEntry_InPunchType", ci);
        GridView1.Columns[7].Caption = rm.GetString("ManualTimeEntry_OutDate", ci);
        GridView1.Columns[8].Caption = rm.GetString("ManualTimeEntry_Out_Time", ci);
        GridView1.Columns[6].Caption = rm.GetString("ManualTimeEntry_OutPunchType", ci);
        GridView1.Columns[9].Caption = rm.GetString("email_Reason", ci);
        GridView1.Columns[10].Caption = rm.GetString("email_Status", ci);
        lblEmpSwipe.Text = rm.GetString("TerminalDataType_Card_No", ci);
        lblTimePeriod.Text = rm.GetString("ShiftExchange_DateRange", ci);
        lblType.Text = rm.GetString("ManualTimeEntryType", ci);
        lblFilter.Text = rm.GetString("lblFilter", ci);
        lblDataView.Text = rm.GetString("lblDataView", ci);
        btnImport.Text = rm.GetString("btnImport", ci);
    }
    private void Userrights()
    {
        ds_Checkuser = objCheckUser.checkRights(26, Convert.ToInt32(Session["userGroup_Id"]), "");
        if (ds_Checkuser.Tables[0].Rows.Count > 0)
        {
            if (ds_Checkuser.Tables[0].Rows[0]["addPrv"] != DBNull.Value && Convert.ToInt32(ds_Checkuser.Tables[0].Rows[0]["addPrv"]) == 1)
            {
                this.btn_Add.Visible = true;
            }
            else
            {
                this.btn_Add.Visible = false;
            }
            if (ds_Checkuser.Tables[0].Rows[0]["modifyPrv"] != DBNull.Value && Convert.ToInt32(ds_Checkuser.Tables[0].Rows[0]["modifyPrv"]) == 1)
            {
                this.GridView1.Columns[14].Visible = true;
            }
            else
            {
                this.GridView1.Columns[14].Visible = false;
            }
            if (ds_Checkuser.Tables[0].Rows[0]["viewPrv"] != DBNull.Value && Convert.ToInt32(ds_Checkuser.Tables[0].Rows[0]["viewPrv"]) == 1)
            {
                this.GridView1.Columns[13].Visible = true;
            }
            else
            {
                this.GridView1.Columns[13].Visible = false;
            }
            if (ds_Checkuser.Tables[0].Rows[0]["deletePrv"] != DBNull.Value && Convert.ToInt32(ds_Checkuser.Tables[0].Rows[0]["deletePrv"]) == 1)
            {
                this.GridView1.Columns[15].Visible = true;
            }
            else
            {
                this.GridView1.Columns[15].Visible = false;
            }
        }
        else
        {
            Response.Redirect("TransactionLandingPage.aspx");
        }
        if (Convert.ToString(Session["UserGroupName"]) == "SuperAdmin" || Convert.ToString(Session["HasSpecialRights"]) == "True")
        {
            lnktbnexcel.Visible = true;
            lnkbtnpdf.Visible = true;
        }
    }
    private void grid_RestoreDefault()
    {
        //Restores the Default view of the grid
        txt_EmpName.Text = string.Empty;
        txtEmployeeId.Text = string.Empty;
        txtStartDate.Text = string.Empty;
        txtEndDate.Text = string.Empty;
        txtSwipeCard.Text = string.Empty;
        ddlType.SelectedIndex = 0;
        GridView1.PageIndex = 0;
        GridView1.DataSourceID = ObjectDataSource1.ID;
    }
    private void FillGrid_Search()
    {
        string empName = txt_EmpName.Text.Trim();
        txt_EmpName.Text = empName;
        string empId = txtEmployeeId.Text.Trim();
        txtEmployeeId.Text = empId;
        string strStartDate = txtStartDate.Text;
        string strEndDate = txtEndDate.Text;
        bool boolErrorStatus = true;
        string gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
        strStartDate = objClassCommon.DateConvertion(gstrDateFormat, strStartDate);
        strEndDate = objClassCommon.DateConvertion(gstrDateFormat, strEndDate);
        string strSwipeCard = "";
        strSwipeCard = txtSwipeCard.Text.ToString().Trim().Replace("'", "''");
        //Checks weather both the start and end order date are available or not available
        if (strStartDate == string.Empty && strEndDate == string.Empty)
        {
            //Both date not given
            boolErrorStatus = false;
        }
        else if (strStartDate != string.Empty && strEndDate != string.Empty)
        {
            //Both date Given            
            if (Convert.ToDateTime(strEndDate).Date < Convert.ToDateTime(strStartDate).Date)
            {
                //Checks weather the start date is less than end date
                base.Message(rm.GetString("Alert_FromDateShouldLesser", ci));
                GridView1.DataSourceID = "";
                return;
                boolErrorStatus = true;
            }
            else
            {
                boolErrorStatus = false;
            }
        }
        else
        {
            //Any one date is given
            GridView1.DataSourceID = "";
            return;
            boolErrorStatus = true;
        }
        if (boolErrorStatus == true)
        {
            grid_RestoreDefault();
        }
        else
        {
            GridView1.PageIndex = 0;
            GridView1.DataSourceID = ObjectDataSource1.ID;
        }
    }
    public void GetEmptyText(object sender, EventArgs e)
    {
        Label lblNoRecords = (Label)sender;
        lblNoRecords.Text = rm.GetString("Alert_Norecordsfound", ci);
    }
    #endregion
    #region GridviewEvents
    protected void GridView1_HtmlRowCreated(object sender, ASPxGridViewTableRowEventArgs e)
    {
        base.Page_Load(sender, e);
        if (e.RowType == GridViewRowType.Data)
        {
            source_Language = Convert.ToString(Session["Session_ActiveLanguage"]);
            rm = new ResourceManager(source_Language, System.Reflection.Assembly.Load("App_GlobalResources"));
            ci = Thread.CurrentThread.CurrentCulture;
            Label lbl_reason = (Label)GridView1.FindRowCellTemplateControl(e.VisibleIndex, null, "lbl_reason");
            Label lbl_InPunchType = (Label)GridView1.FindRowCellTemplateControl(e.VisibleIndex, null, "lbl_InPunchType");
            if (lbl_InPunchType != null)
            {
                switch (lbl_InPunchType.Text)
                {
                    case "In":
                        lbl_InPunchType.Text = rm.GetString("PunchType_In", ci);
                        break;
                    case "Out":
                        lbl_InPunchType.Text = rm.GetString("PunchType_Out", ci);
                        break;
                    case "Shift In":
                        lbl_InPunchType.Text = rm.GetString("PunchType_ShiftIn", ci);
                        break;
                    case "Shift Out":
                        lbl_InPunchType.Text = rm.GetString("PunchType_ShiftOut", ci);
                        break;
                    case "Break In":
                        lbl_InPunchType.Text = rm.GetString("PunchType_BreakIn", ci);
                        break;
                    case "Break Out":
                        lbl_InPunchType.Text = rm.GetString("PunchType_BreakOut", ci);
                        break;
                    case "Lunch In":
                        lbl_InPunchType.Text = rm.GetString("PunchType_LunchIn", ci);
                        break;
                    case "Lunch Out":
                        lbl_InPunchType.Text = rm.GetString("PunchType_LunchOut", ci);
                        break;
                    case "In Duty":
                        lbl_InPunchType.Text = rm.GetString("PunchType_InDuty", ci);
                        break;
                    case "Out Duty":
                        lbl_InPunchType.Text = rm.GetString("PunchType_OutDuty", ci);
                        break;
                    case "Official In":
                        lbl_InPunchType.Text = rm.GetString("PunchType_OfficialIn", ci);
                        break;
                    case "Official Out":
                        lbl_InPunchType.Text = rm.GetString("PunchType_OfficialOut", ci);
                        break;
                }
            }
            Label lbl_OutPunchType = (Label)GridView1.FindRowCellTemplateControl(e.VisibleIndex, null, "lbl_OutPunchType");
            if (lbl_OutPunchType != null)
            {
                switch (lbl_OutPunchType.Text)
                {
                    case "In":
                        lbl_OutPunchType.Text = rm.GetString("PunchType_In", ci);
                        break;
                    case "Out":
                        lbl_OutPunchType.Text = rm.GetString("PunchType_Out", ci);
                        break;
                    case "Shift In":
                        lbl_OutPunchType.Text = rm.GetString("PunchType_ShiftIn", ci);
                        break;
                    case "Shift Out":
                        lbl_OutPunchType.Text = rm.GetString("PunchType_ShiftOut", ci);
                        break;
                    case "Break In":
                        lbl_OutPunchType.Text = rm.GetString("PunchType_BreakIn", ci);
                        break;
                    case "Break Out":
                        lbl_OutPunchType.Text = rm.GetString("PunchType_BreakOut", ci);
                        break;
                    case "Lunch In":
                        lbl_OutPunchType.Text = rm.GetString("PunchType_LunchIn", ci);
                        break;
                    case "Lunch Out":
                        lbl_OutPunchType.Text = rm.GetString("PunchType_LunchOut", ci);
                        break;
                    case "In Duty":
                        lbl_OutPunchType.Text = rm.GetString("PunchType_InDuty", ci);
                        break;
                    case "Out Duty":
                        lbl_OutPunchType.Text = rm.GetString("PunchType_OutDuty", ci);
                        break;
                    case "Official In":
                        lbl_OutPunchType.Text = rm.GetString("PunchType_OfficialIn", ci);
                        break;
                    case "Official Out":
                        lbl_OutPunchType.Text = rm.GetString("PunchType_OfficialOut", ci);
                        break;
                }
            }

            string lbl_InTime = Convert.ToString(e.GetValue("ManualTimeEntry_InTime"));
            string NewTimeFormat = string.Empty;
            string TimeFormat = Convert.ToString(Session["ITimeFormat"]);
            if (TimeFormat == "HH:mm")
            {
                NewTimeFormat = "HH:mm:ss";
            }
            else
            {
                NewTimeFormat = "hh:mm:ss tt";
            }
            if (lbl_InTime != "")
            {
                lbl_InTime = (Convert.ToDateTime(lbl_InTime)).ToString(NewTimeFormat);
                e.Row.Cells[4].Text = lbl_InTime;
            }
            string lbl_OutTime = Convert.ToString(e.GetValue("ManualTimeEntry_OutTime"));
            if (lbl_OutTime != "")
            {
                lbl_OutTime = (Convert.ToDateTime(lbl_OutTime)).ToString(NewTimeFormat.ToString());
                e.Row.Cells[7].Text = lbl_OutTime;
            }
            Label lbl_Status = (Label)GridView1.FindRowCellTemplateControl(e.VisibleIndex, null, "lbl_status");
            if (lbl_Status != null)
            {
                switch (Convert.ToString(lbl_Status.Text))
                {
                    case "Approved":
                        lbl_Status.Text = rm.GetString("btn_Approved", ci);
                        break;
                    case "Forwarded":
                        lbl_Status.Text = rm.GetString("btn_Forwarded", ci);
                        break;
                    case "Pending":
                        lbl_Status.Text = rm.GetString("btn_Pending", ci);
                        break;
                    case "Rejected":
                        lbl_Status.Text = rm.GetString("btn_Reject", ci);
                        break;
                }
            }
            if (lbl_reason != null)
            {
                if (lbl_reason.Text == "Discrepancy Entry")
                {
                    lbl_reason.Text = rm.GetString("Discrepancy_Entry", ci);
                }
                if (Convert.ToString(lbl_reason.Text).Length > 15)
                {
                    e.Row.Cells[8].Text = Convert.ToString(lbl_reason.Text).Substring(0, 15) + "...";
                    e.Row.Cells[8].ToolTip = Convert.ToString(lbl_reason.Text);
                    e.Row.Cells[8].Style.Add("Cursor", "Pointer");
                }
                else
                {
                    e.Row.Cells[8].ToolTip = Convert.ToString(lbl_reason.Text);
                }
            }
        }
    }
    #endregion
    //The below function added by karthikeyan for the Grid view edit and delete
    protected void EditLinkButton_Click(object sender, EventArgs e)
    {

        LinkButton btn = sender as LinkButton;
        int gintManualTimeEntryId = Convert.ToInt32(btn.CommandName);
        string ManuStatus = btn.CommandArgument;
        if (ManuStatus == "Approved")
        {
            if (Convert.ToString(Session["UserGroupName"]) == "SuperAdmin" || Convert.ToString(Session["HasSpecialRights"]) == "True")
            {
                Response.Redirect("../Transactions/TA_UI_Transactions_ManualTimeEntryModify.aspx?MID=" + gintManualTimeEntryId);
            }
            else
            {
                base.Message(rm.GetString("Msg_ApprovedManualTimeEntryCannotbemodified", ci));
                return;
            }
        }
        Response.Redirect("../Transactions/TA_UI_Transactions_ManualTimeEntryModify.aspx?MID=" + gintManualTimeEntryId);
    }
    protected void btn_delete_Click_1(object sender, EventArgs e)
    {
        //ToDo: Add Delete functionality Here 
        LinkButton btn = sender as LinkButton;
        int gintManualTimeEntryId = Convert.ToInt32(btn.CommandName);
        string ManuStatus = btn.CommandArgument;

        string strScript = string.Empty;
        if (ManuStatus.ToString() == "Approved")
        {
            if (Convert.ToString(Session["UserGroupName"]) == "SuperAdmin" || Convert.ToString(Session["HasSpecialRights"]) == "True")
            {
                objManualTimeEntry.DeleteManualTimeEntry(gintManualTimeEntryId, Convert.ToInt32(Session["EmpAutoID"].ToString()));
                strScript = strScript + "<script language='javascript'>";
                strScript = strScript + "alert('" + rm.GetString("Alert_ManualTimeEntryhasbeendeletedsucessfully", ci) + "');";
                strScript = strScript + "location.replace('TA_UI_Transactions_ManualTimeEntry.aspx')";
                strScript = strScript + "</script>";
                Page.RegisterStartupScript("Alert", strScript);
            }
            else
            {
                base.Message(rm.GetString("Alert_ApprovedManualTimeEntryCannotbedeleted", ci));
                return;
            }
        }
        else
        {
            objManualTimeEntry.DeleteManualTimeEntry(gintManualTimeEntryId, Convert.ToInt32(Session["EmpAutoID"].ToString()));
            strScript = strScript + "<script language='javascript'>";
            strScript = strScript + "alert('" + rm.GetString("Alert_ManualTimeEntryhasbeendeletedsucessfully", ci) + "');";
            strScript = strScript + "location.replace('TA_UI_Transactions_ManualTimeEntry.aspx')";
            strScript = strScript + "</script>";
            Page.RegisterStartupScript("Alert", strScript);
        }

    }
    //End

    protected void lnktbnexcel_Click(object sender, EventArgs e)
    {
        LinkButton lnkbtn = (LinkButton)sender;  //Called From  Grid Report Icon click / both excel and pdf
        DisableControls();
        ASPxGridViewExporter1.Landscape = true;
        ASPxGridViewExporter1.LeftMargin = 10;
        ASPxGridViewExporter1.RightMargin = 10;
        ASPxGridViewExporter1.ExportedRowType = DevExpress.Web.GridViewExportedRowType.All;
        ASPxGridViewExporter1.MaxColumnWidth = 400;
        string saveAsFileName = string.Format("List of Manual Time Entry Records - {0:d}", DateTime.Now).Replace("/", "-").Replace(" ", "");
        ASPxGridViewExporter1.FileName = saveAsFileName;
        ASPxGridViewExporter1.PaperKind = System.Drawing.Printing.PaperKind.A3;
        switch (lnkbtn.CommandName)
        {
            case "excel":
                ASPxGridViewExporter1.WriteXlsxToResponse();
                break;
            case "pdf":
                ASPxGridViewExporter1.WritePdfToResponse();
                break;
            case "csv":
                ASPxGridViewExporter1.WriteCsvToResponse();
                break;
        }
    }
    private void DisableControls()
    {
        GridView1.Columns[13].Visible = false;
        GridView1.Columns[14].Visible = false;
        GridView1.Columns[15].Visible = false;
    }

    protected void Timer1_Tick(object sender, EventArgs e)
    {
        FillGrid_Search();
    }

    protected void btnImport_Click(object sender, EventArgs e)
    {
        Response.Redirect("TA_UI_Transactions_ManualEntryImport.aspx");
    }
}
