using System;
using System.Data;
using System.Web.UI;
using System.Globalization;
using System.Resources;
using System.Threading;
using System.IO;
public partial class Transactions_TA_UI_Transactions_LeaveImport : 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();
    LeaveApplicationEventData objLeaveApp = new LeaveApplicationEventData();
    int gintUserId = 0;
    string gstrUserGroupName = string.Empty;
    #endregion
    #region PageLoad
    protected override void Page_Load(object sender, EventArgs e)
    {
        base.Page_Load(sender, e);        
        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"]);
        if (!IsPostBack)
        {
            base.CheckPages(220);
            objCommon.menu("LeaveTransaction", "22");
            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("Uploads/LeaveImport.xls");
            if (File.Exists(strPath))
            {
                byte[] data = System.IO.File.ReadAllBytes(strPath);
                Response.Clear();
                Response.AddHeader("Content-Type", "application/Excel");
                Response.AddHeader("Content-Disposition", "attachment;filename=LeaveImport.csv");
                Response.BinaryWrite(data);
                Response.End();
            }
            else
            {
                Message("Template file is not available in the source file");
                return;
            }
        }
        catch (Exception Ex)
        {
            Message(Ex.ToString());
        }
    }
    protected void btn_Upload_Click(object sender, EventArgs e)
    {
        try
        {
            if (fuleave.HasFile)
            {
                string filename = fuleave.FileName.Substring(fuleave.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 + "\\" + fuleave.FileName);
                    fuleave.SaveAs(strFilePath + "\\" + fuleave.FileName);
                    if (fuleave.PostedFile.ContentLength == fileInfo.Length)
                    {
                        if (fileType == ".csv")
                        {
                            DataSet dsInvalidData = ImportLeaveData(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('Leave data 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();
                                    int tableCount = dsInvalidData.Tables.Count;
                                    if (tableCount > 0)
                                    {
                                        string strMsg = Convert.ToString(dsInvalidData.Tables[tableCount - 1].Rows[0]["Message"]);
                                        strScript = "<script language='javascript'>";
                                        strScript = strScript + "alert('" + (strMsg.Contains("Msg:") ? "Leave data imported successfully" : "Leave data not imported successfully") + "');";
                                        strScript = strScript + "</script>";
                                        Page.RegisterStartupScript("Alert", strScript);
                                    }
                                    else
                                    {
                                        strScript = "<script language='javascript'>";
                                        strScript = strScript + "alert('Leave data 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 (fuleave.HasFile)
                {
                    string StrFilePath = Convert.ToString(Server.MapPath("Uploads")) + "\\" + fuleave.FileName;
                    System.IO.File.Delete(StrFilePath);
                }
            }
            catch
            {
            }
        }
    }
    private void commonAlertMessage(string alertmsg)
    {
        Message(alertmsg);
    }
    protected void btn_Cancel_Click(object sender, EventArgs e)
    {
        try
        {
            Response.Redirect("Transactions_TA_UI_Transactions_LeaveApplication.aspx");
        }
        catch (Exception Ex)
        {
            Message(Ex.ToString());
        }
    }
    #endregion
    #region User Defined Functions
    private void LoadStrings(CultureInfo ci)
    {
        lbl_ImportEmployeeHeader.Text = "Import - Leave Application";
        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()
    {
        ds_Checkuser = objCheckUser.checkRights(22, 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_Transactions_LeaveApplication.aspx");
    }
    private DataSet ImportLeaveData(FileInfo fileInfo)
    {
        string strLine;
        string[] strArray;
        char[] charArray = new char[] { ',' };
        string[] strColumnName = { "Sl.no", "Employee_Code_Id", "FromDate", "ToDate", "LeaveType", "NumberOfDays", "Reason" };
        DataSet dsLeave = new DataSet("dsLeave");
        DataTable dtLeave = dsLeave.Tables.Add("dtLeave");
        foreach (string str in strColumnName)
        {
            dtLeave.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 != dtLeave.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);
            dtLeave.Rows.Add(strArray);
            strLine = sr.ReadLine();
        }
        StringWriter swLeaveData = new StringWriter();
        dsLeave.WriteXml(swLeaveData);
        string strleaveData = Convert.ToString(swLeaveData);
        aFile.Dispose();
        return objLeaveApp.ImportLeaveApplication(strleaveData, Convert.ToInt64(Session["EmpAutoID"]), Convert.ToString(Session["UserGroupName"]));
    }
    protected void btnClear_Click(object sender, EventArgs e)
    {
        grvImportDetails.DataSource = null;
        grvImportDetails.DataBind();
    }
}