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.IO;
using System.Data.OleDb;
using System.Resources;
using System.Globalization;
using System.Threading;
using System.Reflection;
/****************************************************************************************************************************
* Project Name    : TimeCheck                            Started Date  : 26-Aug-2014
* Module          : Import Shift Allocation              Last Modified : 
* Programmer      : A.K.T.Moorthi
* Modified by     : 
****************************************************************************************************************************/
public partial class Transactions_TA_UI_Transaction_ShiftImport : Base.BasePage
{
    #region Variable Declaration
    ResourceManager rm;
    CultureInfo ci;
    FileStream aFile;
    String strScript = String.Empty;
    ShiftAllocationEvendata objShiftAlloc = new ShiftAllocationEvendata();
    cls_Common objcls_Common = new cls_Common();
    #endregion
    #region Page Load Event
    protected override void Page_Load(object sender, EventArgs e)
    {
        try
        {
            // session checking
            base.Page_Load(sender, e);
            grvImportDetails.Styles.CssFilePath = Convert.ToString(Session["GridCSS"]);
            //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"]);
            if (!IsPostBack)
            {
                base.CheckPages(201);
                LoadStrings(ci);
                objcls_Common.menu("ShiftTransaction", "201");
            }
            grvImportDetails.DataSource = Session["ShiftAllocaData"] == null ? null : (DataSet)Session["ShiftAllocaData"];
            grvImportDetails.DataBind();
        }
        catch (Exception Ex)
        {
            Message(Ex.ToString());
        }
    }
    #endregion
    #region Button Events
    protected void btn_btn_Upload(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)
                    {
                        DataSet dstShiftAlloc = ImportShiftData(fileInfo);
                        if (dstShiftAlloc.Tables.Count > 0)
                        {
                            if (dstShiftAlloc.Tables[0].Columns.Contains("Employee_Id"))
                            {
                                Session["ShiftAllocaData"] = dstShiftAlloc;
                                grvImportDetails.DataSource = dstShiftAlloc;
                                grvImportDetails.DataBind();
                                strScript = "<script language='javascript'>";
                                strScript = strScript + "alert('" + rm.GetString("Alert_ImportNotSuccessed", ci) + "');";
                                strScript = strScript + "</script>";
                                Page.RegisterStartupScript("Alert", strScript);
                            }
                            else
                            {
                                grvImportDetails.DataSource = null;
                                grvImportDetails.DataBind();
                                string strMsg = Convert.ToString(dstShiftAlloc.Tables[0].Rows[0]["Message"]);
                                strScript = "<script language='javascript'>";
                                strScript = strScript + "alert('" + rm.GetString(strMsg.Contains("Msg:") ? "Alert_ImportSuccessed" : "Alert_ImportNotSuccessed", ci) + "');";
                                strScript = strScript + "</script>";
                                Page.RegisterStartupScript("Alert", strScript);
                            }
                        }
                    }
                    else
                    {
                        strScript = "<script language='javascript'>";
                        strScript = strScript + "alert('" + rm.GetString("Alert_ErrorinShiftImporting", ci) + "');";
                        strScript = strScript + "</script>";
                        Page.RegisterStartupScript("Alert", strScript);
                    }
                }
                else
                {
                    strScript = "<script language='javascript'>";
                    strScript = strScript + "alert('" + rm.GetString("Alert_TheUploadedfileisnotCsvfile", ci) + "');";
                    strScript = strScript + "</script>";
                    Page.RegisterStartupScript("Alert", strScript);
                }
            }
            else
            {
                strScript = "<script language='javascript'>";
                strScript = strScript + "alert('" + rm.GetString("Alert_Youhavenotspecifiedafile", ci) + "');";
                strScript = strScript + "</script>";
                Page.RegisterStartupScript("Alert", strScript);
            }
        }
        catch (Exception ex)
        {
            string strErr = Convert.ToString(ex.Message);
            strScript = "<script language='javascript' type='text/javascript'>";
            strScript = strScript + "alert('" + strErr.Replace("\r", "").Replace("\n", "") + "');";
            strScript = strScript + "</script>";
            Page.RegisterStartupScript("Alert", strScript);
            if (aFile != null) aFile.Dispose();
        }
        finally
        {
            try
            {
                if (fup_ShiftImport.HasFile)
                {
                    string StrFilePath = Convert.ToString(Server.MapPath("Uploads")) + "\\" + fup_ShiftImport.FileName;
                    System.IO.File.Delete(StrFilePath);
                }
            }
            catch (Exception Ex)
            {
            }
            if (aFile != null) aFile.Dispose();
        }
    }
    protected void btn_Cancel_Click(object sender, EventArgs e)
    {
        try
        {
            Response.Redirect("TA_UI_Transaction_ShiftAllocation.aspx");
        }
        catch (Exception Ex)
        {
            throw Ex;
        }
    }
    protected void btnTemplate_Click(object sender, EventArgs e)
    {
        try
        {
            string strPath = Server.MapPath("Uploads/Shift_Allocation_Import_Template.csv");
            byte[] data = System.IO.File.ReadAllBytes(strPath);
            Response.Clear();
            Response.AddHeader("Content-Type", "application/Excel");
            Response.AddHeader("Content-Disposition", "attachment;filename=Shift_Allocation_Import.csv");
            Response.BinaryWrite(data);
            Response.End();
        }
        catch (Exception Ex)
        {
            throw Ex;
        }
    }
    #endregion
    #region User Define Functions
    private DataSet ImportShiftData(FileInfo fileInfo)
    {
        string strLine;
        string[] strArray;
        char[] charArray = new char[] { ',' };
        string[] strColumnName = { "Employee_Code_Id", "Employee_Name", "Company_Name", "Year", "Mon", "Day1", "Day2", "Day3", "Day4", "Day5", "Day6", "Day7", "Day8", "Day9", "Day10", "Day11", "Day12", "Day13", "Day14", "Day15", "Day16", "Day17", "Day18", "Day19", "Day20", "Day21", "Day22", "Day23", "Day24", "Day25", "Day26", "Day27", "Day28", "Day29", "Day30", "Day31" };
        DataSet dsShift = new DataSet("Dst_ShiftAlloc");
        DataTable dtShift = dsShift.Tables.Add("Tbl_ShiftAlloc");
        foreach (string str in strColumnName)
        {
            dtShift.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 != dtShift.Columns.Count)
        {
            strScript = "<script language='javascript'>";
            strScript = strScript + "alert('" + rm.GetString("Alert_ErrorinShiftImporting", ci) + "');";
            strScript = strScript + "</script>";
            Page.RegisterStartupScript("Alert", strScript);
            return null;
        }
        strLine = sr.ReadLine();
        strArray = null;
        while (strLine != null)
        {
            strArray = strLine.Split(charArray);
            dtShift.Rows.Add(strArray);
            strLine = sr.ReadLine();
        }
        string strWeekOff = string.Empty;
        for (int i = 0; i < lstWeeklyOffDays.Items.Count; i++)
        {
            strWeekOff = (lstWeeklyOffDays.Items[i].Selected ? ((strWeekOff.Trim() == string.Empty) ? lstWeeklyOffDays.Items[i].Value : strWeekOff + "," + lstWeeklyOffDays.Items[i].Value) : strWeekOff);
            lstWeeklyOffDays.Items[i].Selected = false;
        }
        StringWriter strShiftAlloc = new StringWriter();
        dsShift.WriteXml(strShiftAlloc);
        string strAlloc = Convert.ToString(strShiftAlloc);
        aFile.Dispose();
        return objShiftAlloc.EmployeeShiftAllcationImport(strAlloc, strWeekOff, (chkSkip.Checked));
    }
    private void LoadStrings(CultureInfo ci)
    {
        lbl_Header.Text = rm.GetString("Transaction_Shift_Import", ci);
        btn_Upload.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Upload", ci);
        btn_Cancel.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Back", ci);
        btn_Template.Text = "&nbsp;&nbsp;" + rm.GetString("strDownloadTemplate", ci);
        lblWeeklyOffDays.Text = rm.GetString("ShiftAllocationWeeklyOffDays", ci);
        lblImportFilePath.Text = rm.GetString("SelectFileImport", ci);
        lstWeeklyOffDays.Items.Clear();
        lstWeeklyOffDays.Items.Add(new ListItem("  " + rm.GetString("Monday", ci) + "  ", "2"));
        lstWeeklyOffDays.Items.Add(new ListItem("  " + rm.GetString("Tuesday", ci) + "  ", "3"));
        lstWeeklyOffDays.Items.Add(new ListItem("  " + rm.GetString("Wednesday", ci) + "  ", "4"));
        lstWeeklyOffDays.Items.Add(new ListItem("  " + rm.GetString("Thursday", ci) + "  ", "5"));
        lstWeeklyOffDays.Items.Add(new ListItem("  " + rm.GetString("Friday", ci) + "  ", "6"));
        lstWeeklyOffDays.Items.Add(new ListItem("  " + rm.GetString("Saturday", ci) + "  ", "7"));
        lstWeeklyOffDays.Items.Add(new ListItem("  " + rm.GetString("Sunday", ci) + "  ", "1"));
    }
    #endregion
}
