using System;
using System.Data;
using System.Web.UI;
using System.IO;
using System.Resources;
using System.Globalization;
using System.Threading;
/****************************************************************************************************************************
* 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_AutoShiftImport : Base.BasePage
{
    #region VariableDeclaration
    ResourceManager rm;
    CultureInfo ci;
    Cls_CheckUser objCheckUser = new Cls_CheckUser();
    string gstrDateFormat = "dd-MMM-yyyy", strScript = "";
    cls_Common objCommon = new cls_Common();
    char chrImportDelimiter = ',';
    FileStream aFile;
    DataSet ds_Checkuser = new DataSet();
    ShiftAllocationEvendata objShiftApp = new ShiftAllocationEvendata();
    int gintUserId = 0;
    string gstrUserGroupName = string.Empty;
    #endregion
    #region PageLoad
    protected override void Page_Load(object sender, EventArgs e)
    {
        base.Page_Load(sender, e);
        if (!IsPostBack)
        {
            base.CheckPages(0);
            objCommon.menu("ShiftTransaction", "267");
        }
        string source_Language = string.Empty;
        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);
        UserRights();
        gintUserId = Int32.Parse(Session["EmpAutoID"].ToString());
        gstrUserGroupName = Convert.ToString(Session["UserGroupName"]);
        grvImportDetails.Styles.CssFilePath = Convert.ToString(Session["GridCSS"]);
    }
    #endregion
    #region Button Events
    protected void btnTemplate_Click(object sender, EventArgs e)
    {
        try
        {
            string strPath = Server.MapPath("Templates/Auto_Shift_Configuration_Import_Template.csv");
            byte[] data = System.IO.File.ReadAllBytes(strPath);
            Response.Clear();
            Response.AddHeader("Content-Type", "application/Excel");
            Response.AddHeader("Content-Disposition", "attachment;filename=Auto_Shift_Configuration_Import_Template.csv");
            Response.BinaryWrite(data);
            Response.End();
        }
        catch (Exception Ex)
        {
            throw Ex;
        }
    }
    protected void btn_Upload_Click(object sender, EventArgs e)
    {
        try
        {
            if (fuAutoShift.HasFile)
            {
                string filename = fuAutoShift.FileName.Substring(fuAutoShift.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 + "\\" + fuAutoShift.FileName);
                    fuAutoShift.SaveAs(strFilePath + "\\" + fuAutoShift.FileName);
                    if (fuAutoShift.PostedFile.ContentLength == fileInfo.Length)
                    {
                        if (fileType == ".csv")
                        {
                            DataSet dsInvalidData = ImportShiftData(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('Auto Shift 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:") ? "Auto Shift data imported successfully" : "Auto Shift data not imported successfully") + "');";
                                    strScript = strScript + "</script>";
                                    Page.RegisterStartupScript("Alert", strScript);
                                }
                            }
                        }
                    }
                    else
                        commonAlertMessage(rm.GetString("Alert_ErrorinImportingEmployee", ci));
                }
                else
                    commonAlertMessage(rm.GetString("Alert_TheUploadedfileisnotExcelfile", ci));
            }
            else
                commonAlertMessage(rm.GetString("Alert_Youhavenotspecifiedafile", ci));
        }
        catch (Exception Ex)
        {
            string strErr = Convert.ToString(Ex.Message);
            commonAlertMessage(strErr.Replace("\r", "").Replace("\n", ""));
        }
        finally
        {
            try
            {
                if (fuAutoShift.HasFile)
                {
                    string StrFilePath = Convert.ToString(Server.MapPath("Uploads")) + "\\" + fuAutoShift.FileName;
                    System.IO.File.Delete(StrFilePath);
                }
            }
            catch
            {
            }
        }
    }
    private void commonAlertMessage(string alertmsg)
    {
        Message(alertmsg);
    }
     #endregion
    #region User Defined Functions
    private void LoadStrings(CultureInfo ci)
    {
        lbl_ImportEmployeeHeader.Text = "Import - Auto Shift Configuration";
        btn_Upload.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Upload", ci);
        lbl_ImportFilePath.Text = rm.GetString("SelectFileImport", ci);
        btnTemplate.Text = "&nbsp;&nbsp;" + rm.GetString("strDownloadTemplate", ci);
        lbl_IndicatesMandatoryFields.Text = rm.GetString("IndicatesMandatoryFields", ci);
        lblImportNote.Text = rm.GetString("lblChangepassImportant", ci);
        btn_back.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Back", ci);
    }
    private void UserRights()
    {
        //Todo:  //PageId 268 Vaighai
        ds_Checkuser = objCheckUser.checkRights(267, Convert.ToInt32(Session["userGroup_Id"]), "addPrv");
        if (ds_Checkuser.Tables[0].Rows.Count == 0)
        {
            Response.Redirect("TransactionLandingPage.aspx");
        }
    }
    #endregion
    protected void btn_back_Click(object sender, EventArgs e)
    {
        Response.Redirect("TA_UI_Transaction_AutoShiftConfiguration.aspx");
    }
    private DataSet ImportShiftData(FileInfo fileInfo)
    {
        string strLine;
        string[] strArray;
        char[] charArray = new char[] { ',' };
        string[] strColumnName = { "EmployeeId", "Employee_Name", "ShiftId1", "ShiftId2", "ShiftId3", "ShiftId4", "ShiftId5"};
        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)
        {
            string strScript = "";
            strScript = "<script language='javascript'>";
            strScript = strScript + "alert('Import the valid CSV file');";
            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();
        }
        StringWriter swAutoShiftData = new StringWriter();
        dsShift.WriteXml(swAutoShiftData);
        string ShiftData = Convert.ToString(swAutoShiftData);
        aFile.Dispose();
        return objShiftApp.ImportAutoShiftDetails(ShiftData, Convert.ToInt16(Session["EmpAutoID"]), Convert.ToString(Session["UserGroupName"]));
    }
    protected void btnClear_Click(object sender, EventArgs e)
    {
        grvImportDetails.DataSource = null;
        grvImportDetails.DataBind();
    }
}
