using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Configuration;
using System.Diagnostics;

/// <summary>
/// Summary description for ExceptionUtility
/// </summary>
public sealed class ExceptionUtility
{
    private ExceptionUtility()
    {
        //
        // TODO- Add constructor logic here
        //
    }
    public static void LogEvent_Errors(int status, string procedure, string function, string parameters)
    {
        //Get the absolute path for the log file
        string logFile = ConfigurationManager.AppSettings["ErrorLog"].ToString();
        string user = "", user_log = "";
        if (HttpContext.Current.Session["uid"] == null)
        {
            user = "null";
            user_log = "BeforeLogin";
        }
        else
            user_log = user = HttpContext.Current.Session["uid"].ToString();
        //  logFile = logFile + "ErrorLog_" + DateTime.Now.ToString("ddMMyy") + ".txt"; //UMER_MOD 140817 
        // added the user id in the log name to prevent any potentinal locking while writing the log
        logFile = logFile + user_log + "_ErrorLog_" + DateTime.Now.ToString("ddMMyy") + ".txt";
        try
        {
            if (File.Exists(logFile))
            {
                using (StreamWriter writer = new StreamWriter(logFile, true))
                {

                    if (!parameters.Contains('-'))
                    {
                        parameters = parameters.Replace(':', '-');
                        parameters = parameters.Replace(',', ':');
                    }

                    writer.WriteLine(DateTime.Now.ToLongTimeString() + ", " + HttpContext.Current.Request.Url.ToString() + ", " + user + ", " + function + ", " + procedure + ", " + parameters + ", " + status);
                    writer.Dispose();
                    writer.Close();



                }
            }
            else
            {
                StreamWriter writer = File.CreateText(logFile);

                writer.WriteLine(DateTime.Now.ToLongTimeString() + ", " + HttpContext.Current.Request.Url.ToString() + ", " + user + ", " + function + ", " + parameters + ", " + status);

                writer.Dispose();
                writer.Close();
            }
        }
        catch (Exception ex)
        {
        }
    }

    public static void LogException(Exception exc)
    {

        if (!exc.Message.Contains("Thread was being aborted.") && !exc.Message.Contains("ORA-24338: statement handle not executed\n"))
        {
            //Get the absolute path for the log file
            string logFile = ConfigurationManager.AppSettings["ErrorLog"].ToString();
            //UMER_MOD 140817 starts 
            //logFile = logFile + "ErrorLog_" + DateTime.Now.ToString("ddMMyy") + ".txt";
            string user = "", user_log = ""; ;
            if (HttpContext.Current.Session["uid"] == null)
            {
                user = "null";
                user_log = "BeforeLogin";
            }
            else
                user_log = user = HttpContext.Current.Session["uid"].ToString();
            logFile = logFile + user_log + "_ErrorLog_" + DateTime.Now.ToString("ddMMyy") + ".txt";
            //UMER_MOD 140817 ends

            if (File.Exists(logFile))
            {
                using (StreamWriter writer = new StreamWriter(logFile, true))
                {
                    writer.WriteLine("-----------------Start-------------------" + DateTime.Now);
                    //writer.Write("Time- ");
                    writer.WriteLine(DateTime.Now.ToLongTimeString() + ", " + HttpContext.Current.Request.Url + ", " + HttpContext.Current.Session["uid"] + "");
                    writer.WriteLine(exc.StackTrace);
                    if (exc.InnerException != null)
                    {
                        writer.Write("Inner Exception Type- ");
                        writer.WriteLine(exc.InnerException.GetType().ToString());
                        writer.Write("Inner Exception- ");
                        writer.WriteLine(exc.InnerException.Message);
                        writer.Write("Inner Source- ");
                        writer.WriteLine(exc.InnerException.Source);
                        if (exc.InnerException.StackTrace != null)
                        {
                            writer.Write("Inner Stack Trace- ");
                            writer.WriteLine(exc.InnerException.StackTrace);
                        }
                    }
                    writer.Write("Exception Type- ");
                    writer.WriteLine(exc.GetType().ToString());
                    writer.WriteLine("Exception- " + exc.Message);
                    writer.WriteLine("Source- " + exc.Source);
                    writer.WriteLine("Stack Trace- ");
                    if (exc.StackTrace != null)
                    {
                        writer.WriteLine(exc.StackTrace);
                        var st = new StackTrace(exc, true);
                        // Get the top stack frame
                        var frame = st.GetFrame(0);
                        // Get the line number from the stack frame
                        var line = frame.GetFileLineNumber();
                        writer.WriteLine("Line Number- " + line.ToString());
                        writer.WriteLine();
                    }
                    writer.WriteLine("----------------End---------------" + DateTime.Now);
                    writer.Dispose();
                    writer.Close();

                }
            }
            else
            {
                StreamWriter writer = File.CreateText(logFile);

                if (exc.InnerException != null)
                {
                    writer.Write("Inner Exception Type- ");
                    writer.WriteLine(exc.InnerException.GetType().ToString());
                    writer.Write("Inner Exception- ");
                    writer.WriteLine(exc.InnerException.Message);
                    writer.Write("Inner Source- ");
                    writer.WriteLine(exc.InnerException.Source);
                    if (exc.InnerException.StackTrace != null)
                    {
                        writer.Write("Inner Stack Trace- ");
                        writer.WriteLine(exc.InnerException.StackTrace);
                    }
                }
                writer.Write("Exception Type- ");
                writer.WriteLine(exc.GetType().ToString());
                writer.WriteLine("Exception- " + exc.Message);
                writer.WriteLine("Source- " + exc.Source);
                writer.WriteLine("Stack Trace- ");
                if (exc.StackTrace != null)
                {
                    writer.WriteLine(exc.StackTrace);
                    writer.WriteLine();
                }
                writer.WriteLine("----------------End---------------" + DateTime.Now);
                writer.Dispose();
                writer.Close();
            }
            //HttpContext.Current.//Response.Redirect("../ErrorPages/ErrorPage.aspx");
        }
    }
    public bool CheckIfFileIsBeingUsed(string fileName)
    {
        try
        {
            File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.None);
        }
        catch (Exception ex)
        {
            return true;
        }
        return false;
    }
}