/// <summary>
 /// Constructor that will create the ErrorObject based on the Error Id
 /// </summary>
 /// <param name="ErrorId"></param>
 public ErrorObject(int ErrorId, Dictionary<string, string> parameters = null)
 {
     IErrorUtil ErrorUtil = new ErrorUtil();
     ErrorObject ErrorObject = ErrorUtil.GetError(ErrorId);
     this.Id = ErrorObject.Id;
     this.ErrorKey = ErrorObject.ErrorKey;
     this.Code = ErrorObject.Code;
     //If there is no parameters then put the error message as is
     if (parameters == null)
         this.Message = ErrorObject.Message;
     //If parameters is not null then replace each variable in the error message with it's appropriate parameter
     else
     {
         var message = ErrorObject.Message;
         foreach (var parameter in parameters)
         {
             if (ErrorObject.Message.Contains(parameter.Key))
                 message = message.Replace(parameter.Key, parameter.Value);
         }
         this.Message = message;
     }
 }
        protected override Task<HttpResponseMessage> SendAsync(
                 HttpRequestMessage request, CancellationToken cancellationToken)
        {
            LoggingUtility log = LoggerFactory.GetLogger();
            string _requestId = request.Properties["requestId"].ToString();
            ErrorUtil errorUtil = new ErrorUtil();
            RpcAuthenticationResponse _responseEnvelope = new RpcAuthenticationResponse(_requestId);
            LogObject logObject = new LogObject();
            var errorResponse = new HttpResponseMessage();
            var tsc = new TaskCompletionSource<HttpResponseMessage>();

            //Initialize the error to 0 to be able to check later if there is any error in the request
            int Error = 0;

            if (new CommonMethods().IsLegacyFormat(request.RequestUri.OriginalString))
                request = new CommonMethods().CombobulateRequest(request);

            AuthenticationObject authenticationObject = new CommonMethods().GetAuthenticationHeader(request);
            if (authenticationObject == null || authenticationObject.AuthenticationType == null || authenticationObject.ApiUser == null || authenticationObject.SharedSecret == null)
            {
                Error = ErrorKey.ERR_HUB_AUTHENTICATION_FAILED;
                authenticationObject = new AuthenticationObject();
            }

            //Authenticate with pmp
            else
            {
                Error = PmpAuth(authenticationObject);
            }

            //The following logic has been added to enforce xml output by default if no or incompatible application value is specified in the request header
            var responseType = request.GetRequestContext().Url.Request.Headers.Accept.LastOrDefault();
            if (responseType != null && responseType.ToString().ToLower().Equals("application/json"))
                request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            else
                request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));

            if (Error != 0)
            {
                _responseEnvelope.Data.Errors.Add(new ErrorObject(Error));
                errorResponse = new MethodsApi().FormatRpcErrorResponse(request, HttpStatusCode.Unauthorized, _responseEnvelope);
                //R185 Modification
                logObject = new CommonMethods().Authentication_ToLogObject(_requestId, authenticationObject.ApiUser, OperationType, OperationName, authenticationObject, _responseEnvelope.Data.Errors);
                log.InfoJson(logObject);
                tsc.SetResult(errorResponse);
                return tsc.Task;
            }

            //Authentication succeeded...continue with the request
            else
            {
                // This piece of code has been added to unit test this handler
                // In case of success we are returning an empty RpcAuthenticationResponse
                if (xunit)
                {
                    tsc.SetResult(new MethodsApi().FormatRpcErrorResponse(request, HttpStatusCode.OK, _responseEnvelope));
                    return tsc.Task;
                }

                logObject = new CommonMethods().Authentication_ToLogObject(_requestId, authenticationObject.ApiUser, OperationType, OperationName, authenticationObject, _responseEnvelope.Data.Errors);
                log.InfoJson(logObject);
                var rpcResponse = base.SendAsync(request, cancellationToken);

                //Check if request has missing parameters (e.g. does not specify the term id or the offer id in the url)
                if (rpcResponse.Result.StatusCode == HttpStatusCode.NotFound)
                {
                    _responseEnvelope.Data.Errors.Add(new ErrorObject(ErrorKey.ERR_HUB_MISSING_DATA_ARGUMENTS));
                    //Log the error
                    Dictionary<string, string> parameters = new Dictionary<string, string>();
                    parameters.Add("URL", rpcResponse.Result.RequestMessage.RequestUri.PathAndQuery);
                    log.InfoJson(new Methods().Error_ToLogObject(_requestId, authenticationObject.ApiUser, OperationType, operationName.ApiCall.ToString(), parameters, _responseEnvelope.Data.Errors));
                    errorResponse = new MethodsApi().FormatRpcErrorResponse(request, HttpStatusCode.NotFound, _responseEnvelope);
                    tsc.SetResult(errorResponse);
                    return tsc.Task;
                }

                return rpcResponse;
            }
        }
        protected override Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request, CancellationToken cancellationToken)
        {
            LoggingUtility log = LoggerFactory.GetLogger();
            ErrorUtil errorUtil = new ErrorUtil();
            LogObject logObject = new LogObject();
            int Error = 0;
            var tsc = new TaskCompletionSource<HttpResponseMessage>();
            string _requestId;

            var QueryValues = request.GetQueryNameValuePairs().ToDictionary(x => x.Key, x => x.Value);
            QueryValues.TryGetValue("requestId", out _requestId);

            if (String.IsNullOrEmpty(_requestId))
                _requestId = Guid.NewGuid().ToString();

            log.ProcessingDebug(_requestId, "Full request URL:" + request.RequestUri.AbsoluteUri);
            request.Properties.Add("requestId", _requestId);
            AuthenticationResponse _responseEnvelope = new AuthenticationResponse(_requestId);

            if (new CommonMethods().IsArgumentFormat(request.RequestUri.OriginalString))
                request = new CommonMethods().CombobulateArgumentRequest(request);

            if (new CommonMethods().IsLegacyFormat(request.RequestUri.OriginalString))
                request = new CommonMethods().CombobulateRequest(request);

            AuthenticationObject authenticationObject = new CommonMethods().GetAuthenticationHeader(request);

            //If header does not contain the required credentials then add an error to the response envelope else
            if (authenticationObject == null || authenticationObject.AuthenticationType == null || authenticationObject.ApiUser == null || authenticationObject.SharedSecret == null)
            {
                Error = ErrorKey.ERR_HUB_AUTHENTICATION_FAILED;
                authenticationObject = new AuthenticationObject();
            }

            //Check authentication
            else
            {
                Error = Authenticate(authenticationObject, _requestId);
            }

            if (Error != 0)
            {
                Dictionary<string, string> parameters = new Dictionary<string, string>();
                parameters.Add("ApiUser", authenticationObject.ApiUser);
                _responseEnvelope.Data.Errors.Add(new ErrorObject(Error, parameters));
                logObject = new CommonMethods().Authentication_ToLogObject(_requestId, authenticationObject.ApiUser, OperationType, OperationName, authenticationObject, _responseEnvelope.Data.Errors);
                log.InfoJson(logObject);
                var response = FormatErrorResponse(request, HttpStatusCode.OK, _responseEnvelope);
                tsc.SetResult(response);

                return tsc.Task;
            }
            else
            {
                logObject = new CommonMethods().Authentication_ToLogObject(_requestId, authenticationObject.ApiUser, OperationType, OperationName, authenticationObject, _responseEnvelope.Data.Errors);
                log.InfoJson(logObject);
                var Response = base.SendAsync(request, cancellationToken);
                return Response;
            }
        }
        protected override Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request, CancellationToken cancellationToken)
        {
            LoggingUtility log = LoggerFactory.GetLogger();
            ErrorUtil errorUtil = new ErrorUtil();
            LogObject logObject = new LogObject();
            var tsc = new TaskCompletionSource<HttpResponseMessage>();
            string _requestId = request.Properties["requestId"].ToString();
            ProviderAuthenticationResponse _responseEnvelope = new ProviderAuthenticationResponse(_requestId);
            //Initialize the error to 0 to be able to check later if there is any error in the request
            int Error = 0;

            //Get the authentication credentials
            AuthenticationObject authenticationObject = new CommonMethods().GetAuthenticationHeader(request);

            //If header does not contain the required credentials then add an error to the response envelope else
            if (authenticationObject == null || authenticationObject.AuthenticationType == null || authenticationObject.ApiUser == null || authenticationObject.SharedSecret == null)
            {
                Error = ErrorKey.ERR_PROVIDER_AUTHENTICATION_FAILED;
                authenticationObject = new AuthenticationObject();
            }

            //Authenticate with pmp
            else
            {
                Error = PmpAuth(authenticationObject, _requestId);
            }

            //Error different then 0, send back the request with an error message
            if (Error != 0)
            {

                Dictionary<string, string> parameters = new Dictionary<string, string>();
                parameters.Add("ApiUser", authenticationObject.ApiUser);

                //Add the error in the response envelope
                //Edit for R184
                _responseEnvelope.Data.Errors.Add(new ErrorObject(Error, parameters));
                //R185 Modification
                //_responseEnvelope.Data.Errors.Add(new ErrorObject(Error, parameters));

                //Log the error
                //Edit for R184
                logObject = new CommonMethods().Authentication_ToLogObject(_requestId, authenticationObject.ApiUser, OperationType, OperationName, authenticationObject, _responseEnvelope.Data.Errors);
                //R185 Modification
                //logObject = new Methods().Authentication_ToLogObject(_requestId, authenticationObject.ApiUser, OperationType, OperationName, authenticationObject, _responseEnvelope.Data.Errors);
                log.InfoJson(logObject);

                var response = new MethodsApi().FormatProviderErrorResponse(request, HttpStatusCode.OK, _responseEnvelope);

                //Return back the results
                tsc.SetResult(response);

                return tsc.Task;
            }

            //Authentication succeeded...continue with the request
            else
            {
                //Authentication and authorization were successful, log the request and  continue processing
                //Edit for R184
                logObject = new CommonMethods().Authentication_ToLogObject(_requestId, authenticationObject.ApiUser, OperationType, OperationName, authenticationObject, _responseEnvelope.Data.Errors);
                //R185 Modification
                //logObject = new Methods().Authentication_ToLogObject(_requestId, authenticationObject.ApiUser, OperationType, OperationName, authenticationObject, _responseEnvelope.Data.Errors);
                log.InfoJson(logObject);

                // This piece of code has been added to unit test this handler
                // In case of success we are returning an empty ProviderAuthenticationResponse
                if (xunit)
                {
                    tsc.SetResult(new MethodsApi().FormatProviderErrorResponse(request, HttpStatusCode.OK, _responseEnvelope));
                    return tsc.Task;
                }

                var providerResponse = base.SendAsync(request, cancellationToken);

                //Check if request has missing action name (e.g. does not specify the action for liveoffers)
                if (providerResponse.Result.StatusCode == HttpStatusCode.InternalServerError)
                {
                    _responseEnvelope.Data.Errors.Add(new ErrorObject(ErrorKey.ERR_PROVIDER_MISSING_ACTION));
                    var response = new MethodsApi().FormatProviderErrorResponse(request, HttpStatusCode.OK, _responseEnvelope);
                    //Log the error
                    Dictionary<string, string> parameters = new Dictionary<string, string>();
                    parameters.Add("URL", providerResponse.Result.RequestMessage.RequestUri.AbsolutePath);
                    log.InfoJson(new Methods().Error_ToLogObject(_requestId, authenticationObject.ApiUser, OperationType, operationName.ApiCall.ToString(), parameters, _responseEnvelope.Data.Errors));
                    tsc.SetResult(response);
                    return tsc.Task;
                }

                return providerResponse;
            }
        }