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.Resources;
using System.IO;
using DevExpress.Web;
/*
 * Created by       :   Manjula.P
 * Created date     :   20-Aug-2014
 * Descriptions     :   Adding this page for shift export to the client in CSV
 * */
public partial class Transactions_TA_UI_Transaction_ShiftExport : Base.BasePage
{
    #region Variable Declaration
    ResourceManager rm;
    CultureInfo ci;
    ShiftEvenData getShift = new ShiftEvenData();
    GetReports rptEmp = new GetReports();
    cls_Common objCommon = new cls_Common();
    Rpt_Common rptcommon = new Rpt_Common();
    string strFromdate, gstrDateFormat, strTodate;
    #endregion
    #region Page Load Event
    protected override void Page_Load(object sender, EventArgs e)
    {
        try
        {
            // session checking
            base.Page_Load(sender, e);
            //get the culture info to set the language        
            string 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);
            Hidden1.Value = Convert.ToString(Session["IDateFormat"]);
            string strSetAlert = "";
            strSetAlert = strSetAlert + "<script language='javascript'>";
            strSetAlert = strSetAlert + "MaxLengthh('" + rm.GetString("Alert_MaximumLengthis", 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);
            if (!IsPostBack)
            {
                base.CheckPages(202);
                //LoadImageInExport();
                fillShift();
                //txtStartDate.Focus();
                objCommon.menu("ShiftTransaction", "202");
            }
        }
        catch (Exception ex)
        {
            base.Message(ex.Message);
        }
    }
    #endregion
    #region User Defined Functions
    public void LoadImageInExport()
    {
        //ddlExport.Items[0].Attributes["backgroundimage"] = "../images/icn-csv.gif";
        //ddlExport.Items[1].Attributes["title"] = "../images/icn-excel.jpg";
        //ddlExport.Items[0].Attributes.Add("style", "background:url(images/icn-csv.gif);");
    }
    private void LoadStrings(CultureInfo ci)
    {
        lbl_Header.Text = rm.GetString("Transaction_Shift_Export", ci);
        btnExport.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Export", ci);
        btn_Cancel.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Back", ci);
        lblTimePeriod.Text = rm.GetString("btn_Back", ci);
        lblStartDate.Text = rm.GetString("ShiftExchange_DateRange", ci);
        lblEndDate.Text = rm.GetString("email_ToDate", ci);
        lbl_EmployeeName.Text = rm.GetString("email_EmployeeName", ci);
        lbl_EmployeeId.Text = rm.GetString("email_EmployeeId", ci);
        lblShift.Text = rm.GetString("ExportFile_Type", ci);
        lblFilter.Text = rm.GetString("lblFilter", ci);
        lblMandatoryFields.Text = rm.GetString("IndicatesMandatoryFields", ci);
    }
    public void fillShift()
    {
        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();
        }
        ListItem lstItem = new ListItem();
        lstItem.Value = "0";
        lstItem.Text = rm.GetString("ExportData_All", ci);
        ddlShift.Items.Insert(0, lstItem);
        foreach (ListItem item in ddlShift.Items)
        {
            item.Attributes.Add("title", item.Text);
        }
    }
    private DataTable TempShiftAllocation(string dtFrom, string dtTo, string employeeName, string levelId, string EmployeeId, int employeeCategory, int employeeType, string userGroupName, string gradeLevel, string strSwipeCard, int ParentId, int DesignationId, string Gender)
    {
        DataTable dtSift = new DataTable();
        try
        {
            // Get Data from Temporary Shift Allocation
            DataSet dsTempShiftAllocation = new DataSet();
            //Fill Data to Dataset dsTempShiftAllocation
            dsTempShiftAllocation = rptEmp.ExportTempShiftAllocation(Convert.ToInt32(Session["EmpAutoID"]), dtFrom, dtTo, employeeName, levelId, EmployeeId, employeeCategory, employeeType, Convert.ToString(Session["UserGroupName"]), gradeLevel, strSwipeCard, ParentId, DesignationId, Gender);
            //Check the Empty table 
            if (dsTempShiftAllocation.Tables["Table"] == null || dsTempShiftAllocation.Tables["Table"].Rows.Count == 0)
            {
                dtSift = null;
            }
            else
            {
                int fromDay = DateTime.Parse(dtFrom).Day;
                int fromMonth = DateTime.Parse(dtFrom).Month;
                int fromYear = DateTime.Parse(dtFrom).Year;
                int toDay = DateTime.Parse(dtTo).Day;
                int toMonth = DateTime.Parse(dtTo).Month;
                int toYear = DateTime.Parse(dtTo).Year;
                int j = 0;
                DataTable dtShiftShortName = new DataTable();
                dtShiftShortName = rptEmp.GetShiftShortName();
                for (int k = 0; k <= dsTempShiftAllocation.Tables[0].Columns.Count - 3; k++)
                {
                    if (k == 0)
                    {
                        dtSift.Columns.Add("Employee Name");
                    }
                    else if (k == 1)
                    {
                        dtSift.Columns.Add("Employee Id", typeof(string));
                    }
                    else if (k == 2)
                    {
                        dtSift.Columns.Add("Year");
                    }
                    else if (k == 3)
                    {
                        dtSift.Columns.Add("Month");
                    }
                    else if (k == dsTempShiftAllocation.Tables[0].Columns.Count - 5)
                    {
                        dtSift.Columns.Add("Gender");
                    }
                    else if (k == dsTempShiftAllocation.Tables[0].Columns.Count - 4)
                    {
                        dtSift.Columns.Add("Company_Name");
                    }
                    else if (k == dsTempShiftAllocation.Tables[0].Columns.Count - 3)
                    {
                        dtSift.Columns.Add("MonthNo");
                    }
                    else
                    {
                        dtSift.Columns.Add((k - 3).ToString());
                    }
                }
                foreach (DataRow dr in dsTempShiftAllocation.Tables[0].Rows)
                {
                    j = j + 1;
                    dtSift.Rows.Add();
                    Int32 MonthNo = 1;
                    for (int i = 0; i <= dsTempShiftAllocation.Tables[0].Columns.Count - 3; i++)
                    {
                        if (i == 4 && Convert.ToInt32(dr["Month"]) == fromMonth)
                        {
                            if (Convert.ToInt32(dr["Year"]) != fromYear)
                            {
                            }
                            else
                            {
                                i = fromDay + 3;
                            }
                        }
                        if (i > 3 && i < dsTempShiftAllocation.Tables[0].Columns.Count - 5)
                        {
                            foreach (DataRow dRow in dtShiftShortName.Rows)
                            {
                                if (dr[i].ToString() == dRow["Shift_Id"].ToString())
                                {
                                    dtSift.Rows[j - 1][i] = dRow["Shift_ShortName"];
                                }
                                else if (dr[i].ToString() == "-1")
                                {
                                    dtSift.Rows[j - 1][i] = rm.GetString("lbl_Off", ci);
                                }
                            }
                        }
                        else if (i == 3)
                        {
                            DateTimeFormatInfo dtfi = new CultureInfo("en-US", true).DateTimeFormat;
                            string temp = dtfi.GetAbbreviatedMonthName(Convert.ToInt32(dr[i].ToString()));
                            dtSift.Rows[j - 1][i] = temp;
                            MonthNo = Convert.ToInt32(dr[i].ToString());
                        }
                        else if (i == dsTempShiftAllocation.Tables[0].Columns.Count - 5)
                        {
                            dtSift.Rows[j - 1][i] = dr["Gender"];
                        }
                        else if (i == dsTempShiftAllocation.Tables[0].Columns.Count - 4)
                        {
                            dtSift.Rows[j - 1][i] = dr["Company_Name"];
                        }
                        else if (i == dsTempShiftAllocation.Tables[0].Columns.Count - 3)
                        {
                            dtSift.Rows[j - 1][i] = MonthNo;
                        }
                        ////Employee code should comes without zero seris in csv and xls. for that have added once char value at first
                        //else if (i == 1)
                        //{
                        //    dtSift.Rows[j - 1][i] = "'" + dr[i];
                        //}
                        else
                        {
                            dtSift.Rows[j - 1][i] = dr[i];
                        }
                        if (toDay + 3 == i && Convert.ToInt32(dr["Month"]) == toMonth && Convert.ToInt32(dr["Year"]) == toYear)
                        {
                            i = dsTempShiftAllocation.Tables[0].Columns.Count - 6;
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
        return dtSift;
    }
    public void ExporttoCSV()
    {
        gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
        string dtFrom = "", dtTo = "";
        string employeeName = txt_EmpName.Text.Trim();
        string empId = txtEmployeeId.Text.Trim();
        if (txtStartDate.Text != "")
        {
            strFromdate = txtStartDate.Text;
            strFromdate = objCommon.DateConvertion(gstrDateFormat, strFromdate);
            dtFrom = strFromdate;
        }
        if (txtEndDate.Text != "")
        {
            strTodate = txtEndDate.Text;
            strTodate = objCommon.DateConvertion(gstrDateFormat, strTodate);
            dtTo = strTodate;
        }
        string Level = rptcommon.getNodes(Convert.ToInt16(Session["parentLevelId"]), Convert.ToString(Session["LevelRights"]));
        DataSet dsShiftAllocation = new DataSet();
        DataTable dtTempShiftAllocation = new DataTable();
        dsShiftAllocation = rptEmp.ExportShiftAllocation(Convert.ToInt32(Session["EmpAutoID"]), dtFrom, dtTo, employeeName, Level, empId, 0, 0, Convert.ToString(Session["UserGroupName"]), "0", "", Convert.ToInt16(Session["parentLevelId"]), Convert.ToInt32(0), "Both");
        dtTempShiftAllocation = TempShiftAllocation(dtFrom, dtTo, employeeName, Level, empId, 0, 0, Convert.ToString(Session["UserGroupName"]), "0", "", Convert.ToInt16(Session["parentLevelId"]), Convert.ToInt32(0), "Both");
        DataTable dtSift = new DataTable();
        if ((dsShiftAllocation.Tables["Table"] == null || dsShiftAllocation.Tables["Table"].Rows.Count == 0) && (dtTempShiftAllocation != null && dtTempShiftAllocation.Rows.Count != 0))
        {
            dtSift = dtTempShiftAllocation;
        }
        else if ((dsShiftAllocation.Tables["Table"] == null || dsShiftAllocation.Tables["Table"].Rows.Count == 0) && (dtTempShiftAllocation == null || dtTempShiftAllocation.Rows.Count == 0))
        {
            string strMsg;
            strMsg = "<script language='javascript'>";
            strMsg = strMsg + "alert('" + rm.GetString("Alert_Thereisnorecord", ci) + "');";
            strMsg = strMsg + "</script>";
            Page.RegisterStartupScript("Display Message", strMsg);
            return;
        }
        else
        {
            int fromDay = DateTime.Parse(dtFrom).Day;
            int fromMonth = DateTime.Parse(dtFrom).Month;
            int fromYear = DateTime.Parse(dtFrom).Year;
            int toMonth = DateTime.Parse(dtTo).Month;
            int toDay = DateTime.Parse(dtTo).Day;
            int toYear = DateTime.Parse(dtTo).Year;
            int j = 0;
            DataTable dtShiftShortName = new DataTable();
            dtShiftShortName = rptEmp.GetShiftShortName();
            for (int k = 0; k <= dsShiftAllocation.Tables[0].Columns.Count - 3; k++)
            {
                if (k == 0)
                {
                    dtSift.Columns.Add("Employee Name");
                }
                else if (k == 1)
                {
                    dtSift.Columns.Add("Employee Id", typeof(string));
                }
                else if (k == 2)
                {
                    dtSift.Columns.Add("Year");
                }
                else if (k == 3)
                {
                    dtSift.Columns.Add("Month");
                }
                else if (k == dsShiftAllocation.Tables[0].Columns.Count - 5)
                {
                    dtSift.Columns.Add("Gender");
                }
                else if (k == dsShiftAllocation.Tables[0].Columns.Count - 4)
                {
                    dtSift.Columns.Add("Company_Name");
                }
                else if (k == dsShiftAllocation.Tables[0].Columns.Count - 3)
                {
                    dtSift.Columns.Add("MonthNo");
                }
                else
                {
                    dtSift.Columns.Add((k - 3).ToString());
                }
            }
            foreach (DataRow dr in dsShiftAllocation.Tables[0].Rows)
            {
                j = j + 1;
                dtSift.Rows.Add();
                Int32 MonthNo = 1;
                for (int i = 0; i <= dsShiftAllocation.Tables[0].Columns.Count - 3; i++)
                {
                    if (i == 4 && Convert.ToInt32(dr["Month"]) == fromMonth)
                    {
                        if (Convert.ToInt32(dr["Year"]) != fromYear)
                        {
                        }
                        else
                        {
                            i = fromDay + 3;
                        }
                    }
                    if (i > 3 && i < dsShiftAllocation.Tables[0].Columns.Count - 5)
                    {
                        foreach (DataRow dRow in dtShiftShortName.Rows)
                        {
                            if (dr[i].ToString() == dRow["Shift_Id"].ToString())
                            {
                                dtSift.Rows[j - 1][i] = dRow["Shift_ShortName"];
                            }
                            else if (dr[i].ToString() == "-1")
                            {
                                dtSift.Rows[j - 1][i] = rm.GetString("lbl_Off", ci);
                            }
                        }
                    }
                    else if (i == 3)
                    {
                        DateTimeFormatInfo dtfi = new CultureInfo("en-US", true).DateTimeFormat;
                        string temp = dtfi.GetAbbreviatedMonthName(Convert.ToInt32(dr[i].ToString()));
                        dtSift.Rows[j - 1][i] = temp;
                        MonthNo = Convert.ToInt32(dr[i].ToString());
                    }
                    else if (i == dsShiftAllocation.Tables[0].Columns.Count - 5)
                    {
                        dtSift.Rows[j - 1][i] = dr["Gender"];
                    }
                    else if (i == dsShiftAllocation.Tables[0].Columns.Count - 4)
                    {
                        dtSift.Rows[j - 1][i] = dr["Company_Name"];
                    }
                    else if (i == dsShiftAllocation.Tables[0].Columns.Count - 3)
                    {
                        dtSift.Rows[j - 1][i] = MonthNo;
                    }
                    //Employee code should comes without zero seris in csv and xls. for that have added once char value at first
                    //else if (i == 1)
                    //{
                    //    dtSift.Rows[j - 1][i] = "'" + dr[i];
                    //}
                    else
                    {
                        dtSift.Rows[j - 1][i] = dr[i];
                    }
                    if (toDay + 3 == i && Convert.ToInt32(dr["Month"]) == toMonth && Convert.ToInt32(dr["Year"]) == toYear)
                    {
                        i = dsShiftAllocation.Tables[0].Columns.Count - 6;
                    }
                }
            }
            //Check Temporary shift Exists or not 
            Boolean boolTempShiftExists = false;
            if (dtTempShiftAllocation != null)
            {
                foreach (DataRow dRowTempShift in dtTempShiftAllocation.Rows)
                {
                    boolTempShiftExists = false;
                    foreach (DataRow dRowPermanentShift in dtSift.Rows)
                    {
                        if (dRowTempShift["Employee Id"].ToString() == dRowPermanentShift["Employee Id"].ToString() && dRowTempShift["Year"].ToString() == dRowPermanentShift["Year"].ToString() && dRowTempShift["Month"].ToString() == dRowPermanentShift["Month"].ToString())
                        {
                            boolTempShiftExists = true;
                            for (int i = 0; i <= dtTempShiftAllocation.Columns.Count - 1; i++)
                            {
                                if (i > 3)
                                {
                                    if (dRowTempShift[i].ToString() == "0" || dRowTempShift[i].ToString() == "")
                                    {
                                    }
                                    else
                                    {
                                        dRowPermanentShift[i] = dRowTempShift[i];
                                    }
                                }
                            }
                        }
                    }
                    if (boolTempShiftExists == false)
                    {
                        DataRow dRowTemp;
                        dRowTemp = dRowTempShift;
                        dtSift.ImportRow(dRowTemp);
                    }
                }
            }
            DataView dv = dtSift.DefaultView;
            dv.Sort = "[Employee Name],Year,MonthNo ASC";
            dtSift = dv.ToTable();
            gvShiftExport.DataSource = dtSift;
            gvShiftExport.DataBind();
            //gvShiftExport.Columns[0].CellStyle.a
            //gvShiftExport.Columns[0].Style.Add("mso-number-format", "\\@");
            Export_SetCookie objSetCookie = new Export_SetCookie();
            objSetCookie.SetCookie(Convert.ToString(Session["EmpAutoID"]), "ShiftExport");
            if (gvShiftExport.VisibleRowCount > 0)
            {
                //if (ASPxCboExport.Value == null) return;
                expShiftExport.Landscape = true;
                expShiftExport.LeftMargin = 30;
                expShiftExport.RightMargin = 30;
                expShiftExport.ExportedRowType = DevExpress.Web.GridViewExportedRowType.All;
                expShiftExport.MaxColumnWidth = 200;
                switch (ddlExport.SelectedValue.ToString())
                {
                    //case "pdf": expShiftExport.WritePdfToResponse("ShiftExport");
                    //    break;
                    case "xls": expShiftExport.WriteXlsToResponse("ShiftExport");
                        break;
                    //case "rtf": expShiftExport.WriteRtfToResponse("ShiftExport");
                    //    break;
                    case "csv": expShiftExport.WriteCsvToResponse("ShiftExport");
                        break;
                    default:
                        break;
                }
            }
            else
            {
                base.Message("No data to be exported.");
            }
        }
    }
    #endregion
    #region Button Click Events
    protected void btn_Cancel_Click(object sender, EventArgs e)
    {
        try
        {
            Response.Redirect("TA_UI_Transaction_ShiftAllocation.aspx");
        }
        catch (Exception Ex)
        {
            base.Message(Ex.Message);
        }
    }
    protected void btnExport_Click(object sender, EventArgs e)
    {
        try
        {
            gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
            string strStartDate = objCommon.DateConvertion(gstrDateFormat, txtStartDate.Text.Trim());
            string strToDate = objCommon.DateConvertion(gstrDateFormat, txtEndDate.Text.Trim());
            DateTime dtmStartDate = DateTime.Parse(strStartDate);
            DateTime dtmToDate = DateTime.Parse(strToDate);
            int Days = dtmToDate.CompareTo(dtmStartDate);
            if (Days < 0)
            {
                string strMsg;
                strMsg = "<script language='javascript'>";
                strMsg = strMsg + "alert('" + rm.GetString("Msg_FromDateShouldGreaterthanToDate", ci) + "');";
                strMsg = strMsg + "</script>";
                Page.RegisterStartupScript("Display Message", strMsg);
                return;
            }
            ExporttoCSV();
        }
        catch (Exception ex)
        {
            base.Message(ex.Message);
        }
    }
    #endregion
}
