using Helpers.Log;
using log4net;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class app_api_server_audit : System.Web.UI.Page
{
    private JavaScriptSerializer jss = new JavaScriptSerializer();
    private ILog logger = Logger.GetLogger(MethodBase.GetCurrentMethod().DeclaringType.Name);

    protected void Page_Load(object sender, EventArgs e)
    {
        Object response;

        try
        {
            string action = Request["action"];

            if (action != null)
            {
                switch (action.ToString().ToUpper())
                {
                    case "AUDIT":
                        response = this.Audit();
                        break;
                    default:
                        response = new Response
                        {
                            Success = false,
                            Message = string.Format("Action '{0} is not supported'.", action),
                        };
                        break;
                }
            }
            else
            {
                response = new Response
                {
                    Success = false,
                    Message = "Parameter 'Action' can not be empty or null.",
                };
            }
        }
        catch (Exception ex)
        {
            response = new Response
            {
                Success = false,
                Message = "Exception.",
            };

            this.logger.Error(ex);
        }


        Response.Clear();
        Response.ContentType = "application/json; charset=utf-8";
        Response.Write(jss.Serialize(response));
        Response.End();
    }

    private Response Audit()
    {
        Response resp = new Response();
        try
        {
            string connectionString = ConfigurationManager.ConnectionStrings["SYSTEM"].ConnectionString;

            string module = Request["module"];
            string message = Request["message"];
            string level = Request["level"];
            string ev = Request["event"];
            int evObject = Convert.ToInt32(Request["event_obj"]); 

            string user = !string.IsNullOrEmpty(Request["user"]) ? Request["user"] : null;
            string timestamp = Request["timestamp"];
            string timezone = Request["timezone"];

            bool appendIP = Convert.ToBoolean(Request["appendIP"]); 

            //string userHostName = (!string.IsNullOrEmpty(Request.UserHostName)) ? Request.UserHostName.ToString() : string.Empty;
            string userHostAddress = (!string.IsNullOrEmpty(Request.UserHostAddress)) ? Request.UserHostAddress.ToString() : string.Empty;
            string ipAddress = userHostAddress;

            if (appendIP)
            {
                message = string.Format("[{0}] {1}", ipAddress, message); 
            }

            SqlConnection sqlCon = new SqlConnection();
            sqlCon.ConnectionString = connectionString;

            SqlCommand comm = new SqlCommand("SYSTEM.AuditMsg", sqlCon);
            comm.CommandType = CommandType.StoredProcedure;

            SqlParameter sqlParam = new SqlParameter("@moduleName", SqlDbType.VarChar);
            sqlParam.Value = module;
            comm.Parameters.Add(sqlParam);

            sqlParam = new SqlParameter("@message", SqlDbType.VarChar);
            sqlParam.Value = message;
            comm.Parameters.Add(sqlParam);

            sqlParam = new SqlParameter("@levelName", SqlDbType.VarChar);
            sqlParam.Value = level;
            comm.Parameters.Add(sqlParam);

            sqlParam = new SqlParameter("@eventName", SqlDbType.VarChar);
            sqlParam.Value = ev;
            comm.Parameters.Add(sqlParam);

            sqlParam = new SqlParameter("@eventObject", SqlDbType.Int);
            sqlParam.Value = evObject;
            comm.Parameters.Add(sqlParam);

            sqlParam = new SqlParameter("@currentUser", SqlDbType.VarChar);
            sqlParam.Value = !string.IsNullOrEmpty(user) ? user : WebApp.GetUserName();
            comm.Parameters.Add(sqlParam);

            sqlParam = new SqlParameter("@timestamp", SqlDbType.DateTime);
            sqlParam.Value = timestamp;
            comm.Parameters.Add(sqlParam);

            sqlParam = new SqlParameter("@timezone", SqlDbType.VarChar);
            sqlParam.Value = timezone;
            comm.Parameters.Add(sqlParam);

            DataSet ds = Security.DALSecurity.CallSecuredProcedure(sqlCon, comm);

            bool status = true;

            //if (ds != null)
            //{
            //    foreach (DataRow r in ds.Tables[0].Rows)
            //    {
            //        //if (r["Status"].ToString().Equals("OK"))
            //        //{
            //        //    status = true;
            //        //}
            //    }
            //}

            resp = new Response()
            {
                Success = status
            };
        }
        catch (Exception ex)
        {
            resp = new Response()
            {
                Success = false,
                Message = string.Format("Exception while trying to Audit. Exception: {0} .", ex.ToString()),
            };
        }

        return resp;
    }
}