using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Text;
using System.IO;
using System.Globalization;
using System.Data.OracleClient;
using System.Runtime.InteropServices;
using System.Net.Mail;
using System.Collections;

public class Helper
{
    public static string  App_Version ="No Version File Found";
	public Helper()
	{
		//
		// TODO: Add constructor logic here
		//
        string oldPath = Environment.GetEnvironmentVariable("path");
        bool found = oldPath.Contains(ConfigurationManager.AppSettings["EncDllPath"]);
        if (!found)
            System.Environment.SetEnvironmentVariable("Path", ConfigurationManager.AppSettings["EncDllPath"] + oldPath);
	}
    
    public static string dbConnectionLive()
    {
        
        return decryptConnectionString(ConfigurationSettings.AppSettings["DBConnection"]);
    }

    public static string getDate(string text)
    {
        string date;
        if (text.Length < 10)
            date = "";
        else
        {
            date = text.Substring(8, 2) + text.Substring(3, 2) + text.Substring(0, 2);
        }
        return date;
    }

    public static string convertDate(string text)
    {
        string date;
        if (text.Length < 6)
            date = "";
        else
        {
            //date = text.Substring(0, 2) + "-" + text.Substring(3, 2) + "-" + "20" + text.Substring(8, 2);
            date = text.Substring(4) + "-" + text.Substring(2, 2) + "-" + "20" + text.Substring(0, 2);
        }
        return date;
    }

    public static string Mask_CardNumber(string cardNo)
    {

        if (cardNo.Length>=10)
           return cardNo.Substring(1, 6) +"XXXXX"+ cardNo.Substring(cardNo.Length-4);
        else 
           return cardNo;

    }
    public static string Decrypt_String(string input)
    {
        
        string Base24Input = DecryptLibrary.DecryptLibrary.DecryptData(input);
        string oldPath = Environment.GetEnvironmentVariable("path");
        bool found = oldPath.Contains(ConfigurationManager.AppSettings["EncDllPath"]);
        if (!found)
            System.Environment.SetEnvironmentVariable("Path", ConfigurationManager.AppSettings["EncDllPath"] + oldPath);

        StringBuilder output = new StringBuilder();
        rijndael_decrypt(Base24Input, output);

        return output.ToString();

    }
    private static string decryptConnectionString(string connectionString)
    {
        string encryptedUserName_BAse64 = connectionString.Substring(connectionString.ToLower().IndexOf("user id=") + 8, connectionString.ToLower().IndexOf(";password") - connectionString.ToLower().IndexOf("user id=") - 8);
        string encryptedPassword_BAse64 = connectionString.Substring(connectionString.ToLower().IndexOf(";password=") + 10);
        encryptedPassword_BAse64 = encryptedPassword_BAse64.Substring(0, encryptedPassword_BAse64.Length - 1);


        string encryptedUserName = DecryptLibrary.DecryptLibrary.DecryptData(encryptedUserName_BAse64);

        string encryptedPassword = DecryptLibrary.DecryptLibrary.DecryptData(encryptedPassword_BAse64);

        
        //System.Environment.SetEnvironmentVariable("Path", @"D:\published\recon\bin" + ";" + oldPath);
        

        StringBuilder Dec_username = new StringBuilder();
        rijndael_decrypt(encryptedUserName, Dec_username);
        string userName = Dec_username.ToString();

        StringBuilder Dec_password = new StringBuilder();
        rijndael_decrypt(encryptedPassword, Dec_password);
        string password = Dec_password.ToString();

        string tempConnectionString = connectionString.Replace(encryptedUserName_BAse64, userName);
        tempConnectionString = tempConnectionString.Replace(encryptedPassword_BAse64, password);

        return tempConnectionString;
    }

    //public static string dbConnectionLive()
    //{
    //    return ConfigurationSettings.AppSettings["DBConnection"];
    //}
    /*public static string dbEairConnection()
    {
        return ConfigurationSettings.AppSettings["DB_EAIR_Connection"];
    }*/

    [DllImport("EncDecDLL.dll")]
    private static extern void rijndael_decrypt(
        //string key,
        string src,
         StringBuilder string_filled_in_dll
        //ref string res
     );
    public static void PreventMulitpleClicks(Button button)
    {
        button.Attributes.Add("onClick", "this.disabled=true;" + button.Page.ClientScript.GetPostBackEventReference(button, string.Empty).ToString());
    }

    public static string dbConnection()
    {
        string tempConnectionString;
        // mode = "l" live
        // mode = "a" archive
        if (HttpContext.Current.Session["mode"] != null)
        {
            string mode = HttpContext.Current.Session["mode"].ToString();
            if (mode.Equals("l"))
                tempConnectionString = ConfigurationSettings.AppSettings["DBConnection"];
            else
                tempConnectionString = ConfigurationSettings.AppSettings["DBAConnection"];


            return decryptConnectionString(tempConnectionString);
        }
        else
        {
            HttpContext.Current.Response.Redirect("../Business/Default.aspx");
        }
        return "";
    }

    //public static string dbConnection()
    //{
    //    // mode = "l" live
    //    // mode = "a" archive
    //    if (HttpContext.Current.Session["mode"] != null)
    //    {
    //        string mode = HttpContext.Current.Session["mode"].ToString();
    //        if (mode.Equals("l"))
    //            return ConfigurationSettings.AppSettings["DBConnection"];
    //        else
    //            return ConfigurationSettings.AppSettings["DBAConnection"];
    //    }
    //    else
    //    {
    //        HttpContext.Current.Response.Redirect("../Business/Default.aspx");
    //    }
    //    return "";
    //}

    public static int gridSize()
    {
        return int.Parse(ConfigurationSettings.AppSettings["gridsize"]);
    }

    public static int MaxPostSize()
    {
        return int.Parse(ConfigurationSettings.AppSettings["MaxPostSize"]);
    }

    public static String DecPassword(String pass)
    {
        string FsPassWord = "";
        String FsDecPassword = "";
        int pwd;

        for (int nCount = 0; nCount < pass.Length; nCount++)
        {
            FsPassWord = pass.Substring(nCount, 1);
            pwd = ((Encoding.ASCII.GetBytes(FsPassWord)[0]) + 15) - 12;
            FsDecPassword = FsDecPassword + Convert.ToString((Convert.ToChar(pwd)));
        }
        return FsDecPassword;
    }

    public static void writeMWLog(string text)
    {
        string fname = ConfigurationSettings.AppSettings["MWLOG"];//"c:\\MW_LOG.txt";
        StreamWriter sw = File.AppendText(fname);
        sw.WriteLine(text);
        sw.Close();
    }

    public static void Read_APP_VersoinNo()
    {

        try
        {   // Open the text file using a stream reader.
            using (StreamReader sr = new StreamReader(System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath+"version.txt"))
            {
                // Read the stream to a string, and write the string to the console.
                String line = sr.ReadLine();
                Console.WriteLine(line);
                App_Version = line;
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("The file could not be read:");
            Console.WriteLine(e.Message);
        }
      
    }

    public static string formatDate_ToDBFormat(string dateValue)
    {

        string formattedDate;

        formattedDate = DateTime.ParseExact(dateValue, "dd-MM-yyyy", CultureInfo.InvariantCulture).ToString("yyMMdd");

        return formattedDate;
    }

    public static string formatTime_toDBFormat(string timeValue)
    {
        return timeValue.Replace(":", "");
    }

    public static int getCurrentUserGroup(int userId)
    {
        int groupId;

        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "lookup_getter.GET_USER_GROUP";

        oracom.Parameters.Add("p_user_id", OracleType.Number).Direction = ParameterDirection.Input;

        oracom.Parameters.Add("p_group_id", OracleType.Number).Direction = ParameterDirection.Output;

        oracom.Parameters["p_user_id"].Value = userId;

        OracleDataAdapter da = new OracleDataAdapter(oracom);
        DataSet ds = new DataSet();
        da.Fill(ds);

        oracon.Close();

        groupId = int.Parse(oracom.Parameters["p_group_id"].Value.ToString());

        return groupId;
    }

   

    public static string getEventType(int eventId)
    {
        string eventType;

        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "RECON_EVENT_EDITOR.GET_EVENT_TYPE";

        oracom.Parameters.Add("P_RE_CODE", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("P_RE_TYPE", OracleType.VarChar, 3).Direction = ParameterDirection.Output;

        oracom.Parameters["P_RE_CODE"].Value = eventId;

        OracleDataAdapter da = new OracleDataAdapter(oracom);
        DataSet ds = new DataSet();
        da.Fill(ds);

        oracon.Close();

        eventType = oracom.Parameters["P_RE_TYPE"].Value.ToString();

        return eventType;
    }

    public static DataSet getReportEvent(int eventId)
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "poslookup_getter.get_report_event";

        oracom.Parameters.Add("p_event_cd", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_output", OracleType.Cursor).Direction = ParameterDirection.Output;

        oracom.Parameters["p_event_cd"].Value = eventId;

        OracleDataAdapter da = new OracleDataAdapter(oracom);
        DataSet ds = new DataSet();
        da.Fill(ds);

        oracon.Close();

        return ds;
    }

    public static void LogOut(string UID)
    {
        //System.Web.SessionState.HttpSessionState session = HttpContext.Current.Session;
        try
        {
            string DBConnection = Helper.dbConnectionLive();

            OracleConnection oracon = new OracleConnection(DBConnection);
            oracon.Open();

            OracleCommand oracom = new OracleCommand();
            oracom.Connection = oracon;

            oracom.CommandType = CommandType.StoredProcedure;
            oracom.CommandText = "sec_authenticate.authenticate_user_logoff";

            oracom.Parameters.Add("p_current_uid", OracleType.Number).Direction = ParameterDirection.Input;
            oracom.Parameters.Add("p_lang", OracleType.VarChar).Direction = ParameterDirection.Input;
            oracom.Parameters.Add("p_res_code", OracleType.Number).Direction = ParameterDirection.Output;
            oracom.Parameters.Add("p_res_type", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
            oracom.Parameters.Add("p_res_msg", OracleType.VarChar, 250).Direction = ParameterDirection.Output;

            oracom.Parameters["p_lang"].Value = "EN";

            oracom.Parameters["p_current_uid"].Value = UID;


            oracom.ExecuteNonQuery();
            oracon.Close();
        }
        catch (Exception ex)
        {
            //ExceptionUtility.LogException(ex, "sec_authenticate.authenticate_user_logoff", "1.1", "Login_user", "userID -" + UID + /* ":password -" + password +*/":error -" + ex.Message + "");
            //Response.Redirect("../ErrorPages/ErrorPage.aspx");

        }
    }

    public static DataTable GetLookup(string TableName)
    {
        DataTable dtRes = new DataTable();

        try
        {
           
            string DBConnection = Helper.dbConnection();

            OracleConnection oracon = new OracleConnection(DBConnection);

            OracleCommand oraCom = new OracleCommand();
            oraCom.CommandText = "select * From "+TableName;
            oraCom.Connection = oracon;
            OracleDataAdapter da = new OracleDataAdapter(oraCom);


            da.Fill(dtRes);

            return dtRes;


        }
        catch (Exception ex)
        {
            return dtRes;
        }


    }
 

    public static string GetLandingURL(int U_ID)
    {
        try
        {
            DataTable dtRes = new DataTable();

            string DBConnection = Helper.dbConnection();

            OracleConnection oracon = new OracleConnection(DBConnection);

            OracleCommand oraCom = new OracleCommand();
            oraCom.CommandText = "select * From sec_user where u_id =" + U_ID + "";
            oraCom.Connection = oracon;
            OracleDataAdapter da = new OracleDataAdapter(oraCom);


            da.Fill(dtRes);

            if (dtRes.Rows.Count >= 1)
                return dtRes.Rows[0]["LANDING_URL"].ToString();
            else
                return "";


        }
        catch (Exception ex)
        {
            return "";
        }


    }
 
    public static void SetLandingURL(int U_ID, string LANDING_URL)
    {
        try
        {
            string DBConnection = Helper.dbConnection();

            OracleConnection oracon = new OracleConnection(DBConnection);
            oracon.Open();
            OracleCommand oraCom = new OracleCommand();

            oraCom.CommandType = CommandType.Text;
            oraCom.CommandText = "update sec_user set LANDING_URL='" + LANDING_URL + "' where u_id =" + U_ID + "";
            oraCom.Connection = oracon;

            oraCom.ExecuteNonQuery();
            oracon.Close();

        }
        catch (Exception ex)
        {
            return;
        }


    }

    public static bool OracleError(string strError)
    {
        bool error = false;
        if (strError.Contains("ORA-"))
            error = true;
        else
            error = false;
        return error;

    }

    public static string getParamByID(string ID)
    {
        string DBConnection = "";
        try
        {
            DBConnection = Helper.dbConnectionLive();

            OracleConnection oracon = new OracleConnection(DBConnection);
            oracon.Open();

            OracleCommand oracom = new OracleCommand();
            oracom.Connection = oracon;

            oracom.CommandType = CommandType.StoredProcedure;
            oracom.CommandText = "SYSTEM_PARAM_EDITOR.get_parameter_by_id";

            oracom.Parameters.Add("p_current_uid", OracleType.Number).Direction = ParameterDirection.Input;
            oracom.Parameters.Add("p_param_id", OracleType.Number).Direction = ParameterDirection.Input;
            oracom.Parameters.Add("p_lang", OracleType.VarChar).Direction = ParameterDirection.Input;
            oracom.Parameters.Add("p_res_code", OracleType.Number).Direction = ParameterDirection.Output;
            oracom.Parameters.Add("p_res_type", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
            oracom.Parameters.Add("p_res_msg", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
            oracom.Parameters.Add("p_output", OracleType.Cursor).Direction = ParameterDirection.Output;

            oracom.Parameters["p_param_id"].Value = ID;
            oracom.Parameters["p_lang"].Value = "EN";
            oracom.Parameters["p_current_uid"].Value = "1";

            OracleDataAdapter da = new OracleDataAdapter(oracom);
            DataSet ds = new DataSet();
            da.Fill(ds);

            string temp = ds.Tables[0].Rows[0][2].ToString();
            oracon.Close();

            return temp;
        }
        catch (Exception ex)
        {

            ExceptionUtility.LogException(ex, "SYSTEM_PARAM_EDITOR.get_parameter_by_id", "", "getParamByID", "ID :" + ID + DBConnection + "");
            return null;
        }
    }

}
