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.Resources;
using System.Threading;
using System.Reflection;
/*
 * Created by       :   Manjula.P
 * Created Date     :   04-Aug-2014
 * Descriptinos     :   Adding manual group add entry in transaction page with loading date and shift employees
 * */
public partial class Transactions_PopUp_ManualGroupEntry : Base.BasePage
{
    #region Global Variable Declaration
    ManualEntryEventData objManual = new ManualEntryEventData();
    ResourceManager rm;
    CultureInfo ci;
    int loginEmployeeId;
    DataSet ds = new DataSet();
    bool checkRecordExists;
    bool checkLevel;
    ShiftAllocationEvendata obj = new ShiftAllocationEvendata();
    string gstrDateFormat;
    string gstrUserGroupName = string.Empty;
    cls_Common objClassCommon = new cls_Common();
    string strAlert = string.Empty;
    #endregion
    #region Page Load Event
    protected override void Page_Load(object sender, EventArgs e)
    {
        try
        {
            base.Page_Load(sender, e);
            if (Session["UserGroupName"] != null)
            {
                gstrUserGroupName = Convert.ToString(Session["UserGroupName"]);
            }
            checkRecordExists = true;
            string source_Language;
            loginEmployeeId = Int32.Parse(Session["EmpAutoID"].ToString());
            source_Language = Convert.ToString(Session["Session_ActiveLanguage"]);
            rm = new ResourceManager(source_Language, System.Reflection.Assembly.Load("App_GlobalResources"));
            ci = Thread.CurrentThread.CurrentCulture;
            LoadStrings(ci);
            if (!IsPostBack)
            {
                Session["GroupEntryDate"] = null;
                Session["GroupEmployees"] = null;
                Hidden1.Value = Convert.ToString(Session["IDateFormat"]);
                btn_done1.Visible = false;
                fillShift();
                Session["EmployeeIds"] = string.Empty;
            }
            EmployeeBind();
            checkRecordExists = true;
            string strSetAlert = "";
            strSetAlert = strSetAlert + "<script language='javascript'>";
            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_ValiddatemonthMMDDYYHHMMTTT", ci) + "','" + rm.GetString("Alert_PleaseentervalidDateandTime", ci) + "','" + rm.GetString("Alert_Invalidvalueforhours", ci) + "','" + rm.GetString("Alert_Invalidvalueforminites", ci) + "');";
            strSetAlert = strSetAlert + "SetAlertMessages('" + rm.GetString("Alert_EnterValidFromDate", ci) + "');";
            strSetAlert = strSetAlert + "MaxLen('" + rm.GetString("Alert_MaximumLengthis", ci) + "');";
            strSetAlert = strSetAlert + "</script>";
            Page.RegisterStartupScript("SetAlertMessages", strSetAlert);
        }
        catch (Exception ex)
        {
            base.Message(ex.Message);
        }
    }
    #endregion
    #region User Defined Functions
    //Getting Information from resource file and display it in label
    private void LoadStrings(CultureInfo ci)
    {
        butGo.Text = rm.GetString("btn_Go", ci);
        btn_done1.Text = rm.GetString("btn_Ok", ci);
        grv_Shift.Columns[1].Caption = rm.GetString("email_EmployeeId", ci);
        grv_Shift.Columns[2].Caption = rm.GetString("email_EmployeeName", ci);
        lblShift.Text = rm.GetString("ShiftTiming_ShiftName", ci);
        lblDate.Text = rm.GetString("Permission_PermissionDate", ci);
    }
    public void fillShift()
    {
        ShiftEvenData getShift = new ShiftEvenData();
        DataSet ds = new DataSet();
        string strusergroup = string.Empty;
        ds = getShift.SelectShift(Convert.ToString(Session["UserGroupName"]), Convert.ToString(Session["LevelRights"]), 0);
        foreach (DataRow drRow in ds.Tables[0].Rows)
        {
            switch (drRow["Shift_Name"].ToString())
            {
                case "No Shift":
                    drRow["Shift_Name"] = rm.GetString("Caption_NoShift", ci);
                    break;
            }
        }
        if (ds.Tables[0].Rows.Count > 0)
        {
            this.ddlShift.DataSource = ds;
            this.ddlShift.DataTextField = "Shift_Name";
            this.ddlShift.DataValueField = "Shift_Id";
            this.ddlShift.DataBind();
        }
        foreach (ListItem item in ddlShift.Items)
        {
            item.Attributes.Add("title", item.Text);
        }
    }
    public void CheckDate(object s, ServerValidateEventArgs e)
    {
        if (gstrUserGroupName == "SuperAdmin" || Convert.ToString(Session["HasSpecialRights"]) == "True")
        {
            e.IsValid = true;
        }
        else
        {
            if (txt_Date.Text != string.Empty)
            {
                if (txt_Date.Text.Length >= 10)
                {
                    string strDate = string.Empty;
                    gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
                    strDate = objClassCommon.DateConvertion(gstrDateFormat, txt_Date.Text);
                    DateTime dtCurrent = DateTime.Now;
                    DateTime dtDate = DateTime.Parse(strDate);
                    TimeSpan diff = dtCurrent.Subtract(dtDate);
                    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);
                        e.IsValid = false;
                    }
                }
                else
                {
                    e.IsValid = true;
                }
            }
            else
            {
                e.IsValid = true;
            }
        }
    }
    public DataSet EmployeeBind()
    {
        DataSet ds = new DataSet();
        if (txt_Date.Text.Trim() != string.Empty)
        {
            string strShiftDate = txt_Date.Text.Trim();
            DateTime dtmShiftDate = DateTime.Parse(strShiftDate);
            ds = objManual.SelectEmployeeForGroupManual(Convert.ToString(dtmShiftDate.Year), Convert.ToString(dtmShiftDate.Month),
                          Convert.ToString(dtmShiftDate.Day), Convert.ToInt32(ddlShift.SelectedValue));
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                grv_Shift.DataSource = ds.Tables[0];
                grv_Shift.DataBind();
                btn_done1.Visible = true;
                Session["TotalEmployees"] = ds.Tables[0].Rows.Count;
                ViewState["DataEmployee"] = ds.Tables[0];
            }
            else
            {
                grv_Shift.DataSource = null;
                grv_Shift.DataBind();
                btn_done1.Visible = false;
                ViewState["DataEmployee"] = null;
            }
        }
        return ds;
    }
    //public void CheckEmployeeId_CheckBox()
    //{
    //    string strEmpId = "";
    //    strEmpId = (string)Session["EmployeeIds"];
    //    int intEmployeeIdsLength = strEmpId.Length;
    //    char[] Delimit ={ ',' };
    //    string[] Empid = strEmpId.Split(Delimit);
    //    CheckBox deleteChkBxItem = new CheckBox();
    //    foreach (GridViewRow gr in grv_Shift.Rows)
    //    {
    //        string empId = ((Label)gr.FindControl("lbl_EmpId")).Text.ToString();
    //        foreach (string str in Empid)
    //        {
    //            if (str == empId)
    //            {
    //                deleteChkBxItem = (CheckBox)gr.Cells[0].FindControl("deletethis");
    //                deleteChkBxItem.Checked = true;
    //                int intLength = empId.Length;
    //                if (intEmployeeIdsLength > intLength)
    //                {
    //                    int intIndex = strEmpId.IndexOf("," + str + ",");
    //                    if (intIndex != -1)
    //                    {
    //                        strEmpId = strEmpId.Remove(intIndex, (intLength + 1));
    //                    }
    //                    else
    //                    {
    //                        if (strEmpId.IndexOf(str + ",") != -1 && strEmpId.IndexOf(str + ",") == 0)
    //                        {
    //                            strEmpId = strEmpId.Remove(0, (intLength + 1));
    //                        }
    //                        else if (strEmpId.IndexOf("," + str) != -1 && (strEmpId.IndexOf("," + str) + intLength + 1) == intEmployeeIdsLength)
    //                        {
    //                            strEmpId = strEmpId.Substring(0, (intEmployeeIdsLength - (intLength + 1)));
    //                        }
    //                    }
    //                }
    //                else
    //                {
    //                    strEmpId = strEmpId.Replace(empId, "");
    //                }
    //                intEmployeeIdsLength = strEmpId.Length;
    //                Session["EmployeeIds"] = strEmpId;
    //                goto D;
    //            }
    //        }
    //    D: ;
    //    }
    //}
    //protected string GetEmployeeIdsInOtherPagesOfGrid()
    //{
    //    string strPopShiftEmployeeId = null;
    //    if (Session["PopShiftEmpId"] != null)
    //    {
    //        strPopShiftEmployeeId = Convert.ToString(Session["PopShiftEmpId"]);
    //    }
    //    ds = EmployeeBind();
    //    string strEmpId = string.Empty;
    //    string ChkBoxIDs = string.Empty;
    //    foreach (DataRow dr in ds.Tables[0].Rows)
    //    {
    //        if (ChkBoxIDs == "")
    //        {
    //            ChkBoxIDs = dr["Employee_Code_Id"].ToString();
    //        }
    //        else
    //        {
    //            ChkBoxIDs = ChkBoxIDs + "," + dr["Employee_Code_Id"].ToString();
    //        }
    //    }
    //    return ChkBoxIDs;
    //}
    public void SortGrid(string SortColumn, string SortOrder)
    {
        DataTable dtSrch = new DataTable();
        DataView dvSearch = new DataView();
        dtSrch = (DataTable)ViewState["DataEmployee"];
        dvSearch.Table = dtSrch;
        dvSearch.Sort = SortColumn + " " + SortOrder;
        grv_Shift.DataSource = dvSearch;
        grv_Shift.DataBind();
    }
    #endregion
    #region Button Click Events
    protected void butGo_Click(object sender, EventArgs e)
    {
        try
        {
            Session["SelectAllStatus"] = "False";
            Session["EmployeeIds"] = "";
            Session["currentSession"] = Session["parentLevelId"];
            if (txt_Date.Text.Trim() != string.Empty)
            {
                string strShiftDate = txt_Date.Text.Trim();
                DateTime dtmCurrentDateTime = DateTime.Parse(DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString());
                DateTime dtmShiftDate = DateTime.Parse(strShiftDate);
                if (dtmShiftDate > dtmCurrentDateTime)
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Msg_ShiftDategreater", ci) + "');", true);
                    txt_Date.Focus();
                    grv_Shift.DataSource = null;
                    grv_Shift.DataBind();
                    btn_done1.Visible = false;
                    return;
                }
                else
                {
                    EmployeeBind();
                }
            }
            else
            {
                grv_Shift.DataSource = null;
                grv_Shift.DataBind();
                btn_done1.Visible = false;
            }
        }
        catch (Exception ex)
        {
            base.Message(ex.Message);
        }
    }
    protected void btn_done1_Click(object sender, EventArgs e)
    {
        try
        {
            string strSelectedEmployees = hdnId.Value;
            DataSet ds = objManual.SelectEmployeesByIds(strSelectedEmployees);
            ds.Tables[0].Columns.Add("LoginEmployeeId");
            //ds.Tables[0].Columns[3].DefaultValue = Convert.ToString(Session["EmpAutoID"]);
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                ds.Tables[0].Rows[i][3] = Convert.ToString(Session["EmpAutoID"]);
            }
            ds.Tables[0].AcceptChanges();
            Session["GroupEmployees"] = ds;
            Session["GroupEntryDate"] = txt_Date.Text.Trim();
            string str = "<script language=\"javascript\">";
            str = str + "opener.focus();";
            str = str + "opener.location.href = opener.location + '?fl=1&sid=" + Session.SessionID + "';";
            str = str + "self.close();";
            str = str + "</script>";
            Response.Write(str);
        }
        catch (Exception ex)
        {
            base.Message(ex.Message);
        }
    }
    #endregion
    #region GridView Events
    protected void grv_Shift_PageIndexChanged(object sender, EventArgs e)
    {
        try
        {
            // To display the sorted records in the new page if the Vendor has Sorted the Gridview by clicking any header
            if ((ViewState["SortExpression"]) != null)
            {
                string SortColumn = Convert.ToString(ViewState["SortExpression"]);
                string SortOrder = Convert.ToString(Session["SortOrderEmployee"]);
                SortGrid(SortColumn, SortOrder);
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    protected void grv_Shift_Sorting(object sender, GridViewSortEventArgs e)
    {
        ViewState["SortExpression"] = e.SortExpression;
        if (Convert.ToString(Session["SortOrderEmployee"]) == string.Empty)
        {
            Session["SortOrderEmployee"] = "Asc";
        }
        else if (Convert.ToString(Session["SortOrderEmployee"]) == "Asc")
        {
            Session["SortOrderEmployee"] = "Desc";
        }
        else
        {
            Session["SortOrderEmployee"] = "Asc";
        }
        SortGrid(e.SortExpression, Convert.ToString(Session["SortOrderEmployee"]));
    }
    #endregion
}
