using System;
using System.Data;
using System.Globalization;
using System.IO;
using System.Resources;
using System.Text.RegularExpressions;
using System.Threading;
using System.Web.UI;
public partial class Masters_TA_UI_BulkEmployeeConfiguration : Base.BasePage
{
    #region Variable Declaration
    ResourceManager rm;
    CultureInfo ci;
    FileStream aFile;
    String strScript = String.Empty;
    EmployeeEventData objempEvent = new EmployeeEventData();
    userRightsEventData usrRights = new userRightsEventData();
    ManualEntryEventData objManualEntry = new ManualEntryEventData();
    cls_Common objcommon = new cls_Common();
    ImportData ObjImportData = new ImportData();
    public const string MatchEmailPattern =
            @"^(([\w-]+\.)+[\w-]+|([a-zA-Z]{1}|[\w-]{2,}))@"
     + @"((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?
				[0-9]{1,2}|25[0-5]|2[0-4][0-9])\."
     + @"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?
				[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
     + @"([a-zA-Z0-9]+[\w-]+\.)+[a-zA-Z]{1}[a-zA-Z0-9-]{1,23})$";
    #endregion
    protected override void Page_Load(object sender, EventArgs e)
    {
        // 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"]);
        if (!IsPostBack)
        {
            LoadStrings(ci);
            objcommon.menu("EmployeeMaster", "18");
            bindCategory();
        }
        if (Convert.ToString(Session["UserGroupName"]) != "SuperAdmin" && Convert.ToString(Session["HasSpecialRights"]) != "True")
            Response.Redirect("MasterLandingPage.aspx");
    }
    public string Export(DataSet ds)
    {
        string columnnames = "", body = "", record = "";
        foreach (DataColumn col in ds.Tables[0].Columns)
        {
            columnnames = columnnames + " " + col.ColumnName + " " + ",";
        }
        columnnames = columnnames.Substring(0, columnnames.Length - 1);
        foreach (DataRow row in ds.Tables[0].Rows)
        {
            object[] arr = row.ItemArray;
            for (int i = 0; i <= arr.Length - 1; i++)
            {
                if (arr[i].ToString().IndexOf(",") > 0)
                    record = record + " " + arr[i].ToString() + " " + ",";
                else
                    record = record + arr[i].ToString() + ",";
            }
            body = body + record.Substring(0, record.Length - 1) + System.Environment.NewLine;
            record = "";
        }
        return (columnnames + System.Environment.NewLine + body);
    }
    protected void btn_Template_Click(object sender, EventArgs e)
    {
        try
        {
            string strPath = Server.MapPath("Uploads/OtherData_Import_Template.xls");
            if (File.Exists(strPath))
            {
                DataSet ds = new DataSet();
                FileInfo fileInfo = new System.IO.FileInfo(strPath);
                ds = ObjImportData.ReadExcelSheet(fileInfo);
                string strData = Export(ds);
                byte[] data = System.Text.ASCIIEncoding.ASCII.GetBytes(strData);
                Response.Clear();
                Response.AddHeader("Content-Type", "application/Excel");
                Response.AddHeader("Content-Disposition", "attachment;filename=EmployeeSpecificDataUpdate_Template.csv");
                Response.BinaryWrite(data);
                Response.End();
            }
            else
            {
                Message(rm.GetString("Alert_Templatefileisnotavailedinthesourcefile", ci)); ;
                return;
            }
        }
        catch (Exception Ex)
        {
            Message(Ex.ToString());
        }
    }
    protected void btn_Upload_Click(object sender, EventArgs e)
    {
        try
        {
            if (fup_BulkImport.HasFile)
            {
                string filename = fup_BulkImport.FileName.Substring(fup_BulkImport.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_BulkImport.FileName);
                    fup_BulkImport.SaveAs(strFilePath + "\\" + fup_BulkImport.FileName);
                    if (fup_BulkImport.PostedFile.ContentLength == fileInfo.Length)
                    {
                        if (ddlchange.SelectedValue == "0")
                        {
                            Message(rm.GetString("Alert_SelectCategory", ci));
                            return;
                        }
                        if (Convert.ToInt16(ddlchange.SelectedValue) < 7 || Convert.ToInt16(ddlchange.SelectedValue) == 18)  //todo:Vaigai license 16 to 18
                        {
                            if (rdby2n.Checked != true && rdbn2y.Checked != true)
                            {
                                Message(rm.GetString("Alert_Selectchangethestatusfromoption", ci));
                                return;
                            }
                        }
                        int updated = 0;
                        updated = (ddlchange.SelectedValue == "20") ? ImportLeaveBalanceData(fileInfo) : ImportEmployeeSpecificData(fileInfo);
                        if (updated > 0)
                        {
                            ddlchange.SelectedValue = "0";
                            rdbn2y.Checked = false;
                            rdby2n.Checked = false;
                            Message(rm.GetString("Alert_Fileisimportedsuccessfully", ci));
                        }
                    }
                    else
                        Message(rm.GetString("Alert_ErrorinImporting_BulkConfiguration", ci));
                }
                else
                    Message(rm.GetString("Alert_TheUploadedfileisnotCsvfile", ci));
            }
            else
                Message(rm.GetString("Alert_Youhavenotspecifiedafile", ci));
        }
        catch (Exception ex)
        {
            string strErr = Convert.ToString(ex.Message);
            Message(strErr.Replace("\r", "").Replace("\n", ""));
            if (aFile != null) aFile.Dispose();
        }
        finally
        {
            try
            {
                if (fup_BulkImport.HasFile)
                {
                    string StrFilePath = Convert.ToString(Server.MapPath("Uploads")) + "\\" + fup_BulkImport.FileName;
                    System.IO.File.Delete(StrFilePath);
                }
            }
            catch (Exception Ex)
            {
                Message("Final Block: " + Ex.ToString());
            }
            if (aFile != null) aFile.Dispose();
        }
    }
    #region User Define Functions
    private int ImportLeaveBalanceData(FileInfo fileInfo)
    {
        int Updated = 0;
        try
        {
            string strLine;
            string[] strArray;
            char[] charArray = new char[] { ',' };
            string[] strColumnName = { "Sl.No", "EmployeeID", "Employee Name", "LeaveType1", "LeaveType2", "LeaveType3", "LeaveType4", "LeaveType5", "LeaveType6", "LeaveType7", "LeaveType8", "LeaveType9", "LeaveType10", "LeaveType11", "LeaveType12", "LeaveType13", "LeaveType14", "LeaveType15" };
            DataSet dsLeaveBalance = new DataSet("dsLeaveBalance");
            DataTable dtLeaveBalance = dsLeaveBalance.Tables.Add("TblLeaveBalance");
            foreach (string str in strColumnName)
            {
                dtLeaveBalance.Columns.Add(str);
            }
            FileStream aFile = new FileStream(fileInfo.FullName.ToString(), FileMode.Open);
            StreamReader sr = new StreamReader(aFile);
            strLine = sr.ReadLine();
            strArray = strLine.Split(charArray);
            if (strArray.Length != dtLeaveBalance.Columns.Count)
            {
                Message(rm.GetString("Alert_ErrorinShiftImporting", ci));
                return 0;
            }
            strLine = sr.ReadLine();
            strArray = null;
            while (strLine != null)
            {
                strArray = strLine.Split(charArray);
                DataRow dr = dtLeaveBalance.NewRow();
                for (int i = 0; i <= strArray.GetUpperBound(0); i++)
                {
                    dr[i] = strArray[i].ToString();
                }
                dtLeaveBalance.Rows.Add(dr);
                strLine = sr.ReadLine();
            }
            sr.Close();
            StringWriter swLeaveBalance = new StringWriter();
            dsLeaveBalance.WriteXml(swLeaveBalance);
            string strLeavebalance = Convert.ToString(swLeaveBalance);
            aFile.Dispose();
            LeaveEventData objleave = new LeaveEventData();
            objleave.ImportPreviousYearLeaveBalance(strLeavebalance);
            Updated = 1;
        }
        catch (Exception)
        {
            Updated = 0;
        }
        return Updated;
    }
    private int ImportEmployeeSpecificData(FileInfo fileInfo)
    {
        int Updated = 0;
        try
        {
            string strLine;
            string validationMsg = string.Empty;
            string[] strArray;
            char[] charArray = new char[] { ',' };
            DataSet dsBulkImport = new DataSet("Dst_bulkimport");
            DataTable dtBulkImport = dsBulkImport.Tables.Add("EmployeeBulkImport");
            dtBulkImport.Columns.Add("Employee_Id");
            dtBulkImport.Columns.Add("UserGroup");
            dtBulkImport.Columns.Add("EmailID");
            dtBulkImport.Columns.Add("PersonalEmailID");
            dtBulkImport.Columns.Add("ContactAddress");
            dtBulkImport.Columns.Add("PermanentAddress");
            dtBulkImport.Columns.Add("PhoneNumber");
            dtBulkImport.Columns.Add("MobileNumber");
            dtBulkImport.Columns.Add("ReportingTo");
            dtBulkImport.Columns.Add("ApprovalAuthority");
            dtBulkImport.Columns.Add("InActive");
            dtBulkImport.Columns.Add("BasicSalary");
            dtBulkImport.Columns.Add("Mobile Clock InOut ");
            dtBulkImport.Columns.Add("SMSEnabled ");

            aFile = new FileStream(fileInfo.FullName.ToString(), FileMode.Open);
            StreamReader sr = new StreamReader(aFile);
            strLine = sr.ReadLine();
            strArray = strLine.Split(charArray);

            if (strArray.Length != 14)  //12 become 14
            {
                Message(rm.GetString("Alert_ImportthevalidCSVfile", ci));
                return 0;
            }

            if (strArray.Length != dtBulkImport.Columns.Count)
            {
                Message(rm.GetString("Alert_ImportthevalidCSVfile", ci));
                return 0;
            }

            strLine = sr.ReadLine();
            strArray = null;
            if (strLine == null)
            {
                Message(rm.GetString("Alert_Thereisnorecordinthefile", ci));
                return 0;
            }
            else
            {
                while (strLine != null)
                {
                    strArray = strLine.Split(charArray);
                    if (strArray[0].Trim().Replace("\"", "") == string.Empty)
                    {
                        validationMsg = rm.GetString("Alert_PleasefillEmployeeCodeforallemployees", ci);
                        sr.Dispose();
                        aFile.Dispose();
                        Message(validationMsg.Replace("\r", "").Replace("\n", ""));
                        return 0;
                    }
                    else
                    {
                        DataSet dsEmpAutoId = new DataSet();
                        dsEmpAutoId = objManualEntry.getEmployeeAutoIdForImport(Convert.ToString(strArray[0]));
                        if (dsEmpAutoId.Tables[0].Rows.Count == 0)
                        {
                            validationMsg = "Invalid Employee ID - " + Convert.ToString(strArray[0]) + ". Kindly remove and import the file once again.";
                            Message(validationMsg.Replace("\r", "").Replace("\n", ""));
                            sr.Dispose();
                            aFile.Dispose();
                            return 0;
                        }
                    }
                    if (ddlchange.SelectedValue != "0")
                    {
                        switch (ddlchange.SelectedValue)
                        {
                            case "7":
                                if (strArray[1].Trim().Replace("\"", "") == string.Empty)
                                {
                                    validationMsg = "Please fill User Group for all employees";
                                    return CommonCoding(validationMsg, sr);
                                }
                                else
                                {
                                    //validate usergroup is available or not.
                                    DataSet ds = new DataSet();
                                    ds = usrRights.checkDuplication(Convert.ToString(strArray[1]).Trim().Replace("'", "''"));
                                    if (ds.Tables[0].Rows.Count == 0)
                                    {
                                        validationMsg = "Invalid Usergroup Name - " + Convert.ToString(strArray[1]) + ". Kindly remove and import the file once again.";
                                        return CommonCoding(validationMsg, sr);
                                    }
                                }
                                break;
                            case "8":
                                if (strArray[2].Trim().Replace("\"", "") == string.Empty)
                                {
                                    validationMsg = "Please fill Official Email ID for all employees";
                                    return CommonCoding(validationMsg, sr);
                                }
                                else
                                {
                                    if (IsEmail(strArray[2].Trim().Replace("\"", "")) == false)
                                    {

                                        validationMsg = "Invalid Email ID - " + Convert.ToString(strArray[2]) + ". Kindly remove and import the file once again.";
                                        return CommonCoding(validationMsg, sr);
                                    }
                                }
                                break;
                            case "9":
                                if (strArray[3].Trim().Replace("\"", "") == string.Empty)
                                {
                                    validationMsg = "Please fill Personal Email ID for all employees";
                                    return CommonCoding(validationMsg, sr);
                                }
                                else
                                {
                                    if (IsEmail(strArray[2].Trim().Replace("\"", "")) == false)
                                    {
                                        validationMsg = "Invalid Email ID - " + Convert.ToString(strArray[2]) + ". Kindly remove and import the file once again.";
                                        return CommonCoding(validationMsg, sr);
                                    }
                                }
                                break;
                            case "10":
                                if (strArray[4].Trim().Replace("\"", "") == string.Empty)
                                {
                                    validationMsg = "Please fill Contact Address for all employees";
                                    return CommonCoding(validationMsg, sr);
                                }
                                break;
                            case "11":
                                if (strArray[5].Trim().Replace("\"", "") == string.Empty)
                                {
                                    validationMsg = "Please fill Permanent Address for all employees";
                                    return CommonCoding(validationMsg, sr);
                                }
                                break;
                            case "12":
                                if (strArray[6].Trim().Replace("\"", "") == string.Empty)
                                {
                                    validationMsg = "Please fill Phone Number for all employees";
                                    return CommonCoding(validationMsg, sr);
                                }
                                break;
                            case "13":
                                if (strArray[7].Trim().Replace("\"", "") == string.Empty)
                                {
                                    validationMsg = "Please fill Mobile Number for all employees";
                                    return CommonCoding(validationMsg, sr);
                                }
                                break;
                            case "14":
                                if (strArray[8].Trim().Replace("\"", "") == string.Empty)
                                {
                                    validationMsg = "Please fill Reporting To for all employees";
                                    return CommonCoding(validationMsg, sr);
                                }
                                break;
                            case "15":
                                if (strArray[9].Trim().Replace("\"", "") == string.Empty)
                                {
                                    validationMsg = "Please fill Leave Sanctioning for all employees";
                                    return CommonCoding(validationMsg, sr);
                                }
                                break;
                            case "17":
                                if (strArray[11].Trim().Replace("\"", "") == string.Empty)
                                {
                                    validationMsg = "Please fill Basic Salary for all employees";
                                    return CommonCoding(validationMsg, sr);
                                }
                                break;


                        }
                    }
                    dtBulkImport.Rows.Add(strArray);
                    strLine = sr.ReadLine();
                }
            }
            StringWriter strwriter = new StringWriter();
            dsBulkImport.WriteXml(strwriter);
            aFile.Dispose();
            objempEvent.EmployeeBulkConfiguration(Convert.ToString(strwriter), Convert.ToInt32(ddlchange.SelectedValue), (rdby2n.Checked == true) ? 1 : 0);
            Updated = 1;
        }
        catch
        {
            Updated = 0;
        }
        return Updated;
    }

    private int CommonCoding(string validationMsg, StreamReader sr)
    {
        Message(validationMsg.Replace("\r", "").Replace("\n", ""));
        sr.Dispose();
        aFile.Dispose();
        return 0;
    }

    public static bool IsEmail(string email)
    {
        if (email != null) return Regex.IsMatch(email, MatchEmailPattern);
        else return false;
    }
    private void LoadStrings(CultureInfo ci)
    {
        btnLeaveTemplate.Text = rm.GetString("LeaveBalanceImportTemplate", ci);
        lbl_Header.Text = rm.GetString("btn_BulkConfiguration", ci);
        lblMandatoryFields.Text = rm.GetString("IndicatesMandatoryFields", ci);
        lblImportFilePath.Text = rm.GetString("SelectFile", ci);
        lblEligible.Text = rm.GetString("lblCategory", ci);
        lblChange.Text = rm.GetString("lblChangethestatus", ci);
        rdby2n.Text = rm.GetString("ShiftSetting_Yes", ci);
        rdbn2y.Text = rm.GetString("ShiftSetting_No", ci);
        btn_Template.Text = "&nbsp;&nbsp;" + rm.GetString("strDownloadTemplate", ci);
        btn_Upload.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Upload", ci);
        btnBack.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Back", ci);
        lblImportNote.Text = rm.GetString("Field_ImportantNote", ci);
    }
    #endregion
    protected void btnBack_Click(object sender, EventArgs e)
    {
        Response.Redirect("TA_UI_Master_Employee.aspx");
    }
    private void bindCategory()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("ID", typeof(int));
        dt.Columns.Add("Text", typeof(string));
        dt.Rows.Add(0, "-Select-");
        dt.Rows.Add(1, "Over Time Eligible");
        dt.Rows.Add(2, "Comp off  Eligible");
        dt.Rows.Add(3, "Over Time & Comp off  Eligible");
        dt.Rows.Add(4, "Report Exclude");
        dt.Rows.Add(6, "Hostel");
        dt.Rows.Add(7, "User Group");
        dt.Rows.Add(8, "Official Email ID");
        dt.Rows.Add(9, "Personal Email ID");
        dt.Rows.Add(10, "Contact Address");
        dt.Rows.Add(11, "Permanent Address");
        dt.Rows.Add(12, "Phone Number");
        dt.Rows.Add(13, "Mobile Number");
        dt.Rows.Add(14, "Reporting To");
        dt.Rows.Add(15, "Approval Authority");
        dt.Rows.Add(16, "InActive");
        dt.Rows.Add(17, "Basic Salary");
        dt.Rows.Add(18, "Mobile Clock InOut");
        dt.Rows.Add(19, "SMSEnabled");
        dt.Rows.Add(20, "Previous Year Leave Balance");


        ddlchange.DataSource = dt;
        ddlchange.DataBind();
        if (dt.Rows.Count > 0)
        {
            ddlchange.DataSource = dt;
            ddlchange.DataTextField = "Text";
            ddlchange.DataValueField = "ID";
            ddlchange.DataBind();
        }
        dt.Dispose();
        foreach (System.Web.UI.WebControls.ListItem item in ddlchange.Items)
        {
            item.Attributes.Add("title", item.Text);
        }
    }
    protected void btnLeaveTemplate_Click(object sender, EventArgs e)
    {
        try
        {
            DataSet dsLeaveTypes = new DataSet();
            LeaveEventData objleave = new LeaveEventData();
            dsLeaveTypes = objleave.SelectLeaveTypeDetails("Superadmin");
            DataSet ds = new DataSet();
            string strFilePath = Server.MapPath("Uploads/LeaveBalance_Import_Template.xls");
            FileInfo fileInfo = new System.IO.FileInfo(strFilePath);
            if (!fileInfo.Exists)
            {
                Message(rm.GetString("Alert_Templatefileisnotavailedinthesourcefile", ci));
                return;
            }
            ds = ObjImportData.ReadExcelSheet(fileInfo);
            if (dsLeaveTypes.Tables.Count > 0 && dsLeaveTypes.Tables[0].Rows.Count > 0)
            {
                if (ds.Tables.Count > 0)
                {
                    for (int i = 0; i < dsLeaveTypes.Tables[0].Rows.Count; i++)
                    {
                        ds.Tables[0].Columns.Add(Convert.ToString(dsLeaveTypes.Tables[0].Rows[i]["leaveType"]));
                    }
                }
                if (dsLeaveTypes.Tables[0].Rows.Count < 15)
                {
                    for (int i = dsLeaveTypes.Tables[0].Rows.Count + 1; i <= 15; i++)
                    {
                        ds.Tables[0].Columns.Add(Convert.ToString("LeaveType " + i));
                    }
                }
            }
            string strData = Export(ds);
            byte[] data = System.Text.ASCIIEncoding.ASCII.GetBytes(strData);
            Response.Clear();
            Response.AddHeader("Content-Type", "application/Excel");
            Response.AddHeader("Content-Disposition", "attachment;filename=LeaveBalance_Import_Template.csv");
            Response.BinaryWrite(data);
            Response.End();
        }
        catch
        {
            Message(rm.GetString("MessageOLEDB_Error", ci));
        }
    }
}
