using LHDN.CRM.BC;
using LHDN.CRM.BC.Services;
using LHDN.CRM.WebAPI.CallCentre.Controllers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Web.Http.Filters;
using LHDN.CRM.BC.Common;
using System.Web.Helpers;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Text;

namespace LHDN.CRM.WebAPI.CallCentre.Filters
{
    public class APIErrorHandlerAttribute : FilterAttribute, IExceptionFilter
    {
        public Task ExecuteExceptionFilterAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken)
        {
            var ex = actionExecutedContext.Exception;

            if (!(ex is HttpResponseException))
            {
                actionExecutedContext.Response = new HttpResponseMessage()
                {
                    StatusCode = System.Net.HttpStatusCode.InternalServerError,
                    Content = new StringContent("{\"Message\": \"" + Constant.WebRequest.InternalError + "\"}", Encoding.UTF8, "application/json")

                };
            }

            return Task.Factory.StartNew(() =>
            {
                Task.Factory.StartNew(() =>
                {
                    BaseApiController baseController = new BaseApiController();
                    baseController.LogError(ex.Message + " " + ex.StackTrace, "SYSTEM");
                });

            }, cancellationToken);
        }
    }
}