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;

public class Helper
{
    public static string App_Version = "No Version File Found";

	public Helper()
	{
		//
		// TODO: Add constructor logic here
		//
	}
    // Brought from Encrypt/Decrupt
    public static string EncryptData(string txtData)
    {
        try
        {
            byte[] passBytes = System.Text.Encoding.Unicode.GetBytes(txtData);
            string encryptData = Convert.ToBase64String(passBytes);
            return encryptData;
        }
        catch (Exception Ex)
        {

            return "-1";
        }
    }
    // Brought from Encrypt/Decrupt
    public static string DecryptData(string encryptedData)
    {
        try
        {
            byte[] passByteData = Convert.FromBase64String(encryptedData);
            string originaldData = System.Text.Encoding.Unicode.GetString(passByteData);
            return originaldData;

        }
        catch (Exception Exp)
        {
            return "-1";
        }
    }

    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 decimal Get_VAT_Rate()
    {
        if (HttpContext.Current.Session["VAT_RATE"] == null)
            HttpContext.Current.Session["VAT_RATE"] = Helper.getParamByID("14"); // VAT

        return Convert.ToDecimal(HttpContext.Current.Session["VAT_RATE"]);
    }
     public static bool IsMultiCurrencyProduct_CS(string product)
     {
         string multiCurrencyProducts = "";
         if (HttpContext.Current.Session["MultiCurrency_Products"] == null)
             HttpContext.Current.Session["MultiCurrency_Products"] = multiCurrencyProducts = Helper.getParamByID("315"); // MultiCurrency Products
         else
             multiCurrencyProducts = HttpContext.Current.Session["MultiCurrency_Products"] as string;

         if (multiCurrencyProducts.Contains("("+product+")" ))
             return true;
         else
         return false;
     }
   
    public static string getParamByID(string ID)
    {
        string DBConnection = Helper.dbConnectionLive();

        OracleConnection oracon = new OracleConnection(DBConnection);
        //Helper.writeMWLog(DBConnection);
        oracon.Open();
        //Helper.writeMWLog("CONNECTED SUCCESSFULLY");
        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;
    }

    public static string dbConnectionLive()
    {
        return DecryptLibrary.DecryptLibrary.DecryptData(ConfigurationSettings.AppSettings["DBConnection"]);
    }

    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 DecryptLibrary.DecryptLibrary.DecryptData(ConfigurationSettings.AppSettings["DBConnection"]);
            else
                return DecryptLibrary.DecryptLibrary.DecryptData(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 gridSize(string pageName)
    {
        int gSize = 10; //10 by defult
        try
        {
            gSize = int.Parse(ConfigurationSettings.AppSettings["gridsize_" + pageName]);
        }
        catch (Exception ex)
        {

            gSize = gridSize();
        }

        return gSize;

    }
    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)
    {

        try
        {

        string fname = ConfigurationSettings.AppSettings["MWLOG"];//"c:\\MW_LOG.txt";
        //UMER_MOD 150317 starts
        string file_date;
        file_date = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString().PadLeft(2, '0') + DateTime.Now.Day.ToString().PadLeft(2, '0');

            string userID = ""; ;
            if (HttpContext.Current.Session["uid"] == null)
                userID = "NoAuthUser";
            else
                userID = HttpContext.Current.Session["uid"].ToString();


            fname = fname + "\\" + userID + "_MQ_MSG_FE_" + file_date + ".log";
            //UMER_MOD 150317 ends
            StreamWriter sw = File.AppendText(fname);
            sw.WriteLine(text);
            sw.Close();

        }
        catch (Exception ex)
        {
            ;// Exceptoin during logging should be capture
        }
    }


    public static void Read_APP_VersionNo()
    {
        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 Read_Version()
    {
        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);
        }

        return App_Version;
    }

    public static void writeLog(string text)
    {
        string fname = ConfigurationSettings.AppSettings["AppLog"];//"c:\\MW_LOG.txt";
        string file_date;
        file_date = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString().PadLeft(2, '0') + DateTime.Now.Day.ToString().PadLeft(2, '0');
        fname = fname + "\\Application_" + file_date + ".log";
        
        StreamWriter sw = File.AppendText(fname);
        sw.WriteLine(text);
        sw.Close();
    }


    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;
    }
}
