using LHDN.CRM.BC.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Helpers;
using System.Web.Http;
using System.Web.Http.Controllers;

namespace LHDN.CRM.WebAPI.Filters
{
    public class ValidateAjaxRequestAttribute : AuthorizeAttribute
    {
        protected override bool IsAuthorized(HttpActionContext actionContext)
        {
            IEnumerable<string> tokenHeaders;
            var IsValidStaticReqVeriCode = actionContext.Request.Headers.TryGetValues("RequestVerificationToken", out tokenHeaders);

            if (IsValidStaticReqVeriCode)
                return IsValidStaticApiKey(tokenHeaders);
            else
            {
                return false;
            }
        }

        protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
        {
            HttpError REQUEST_NOT_AUTHORIZED = new HttpError("CRM Form Authorization has been denied for this request.");

            actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.Forbidden, REQUEST_NOT_AUTHORIZED);
            //base.HandleUnauthorizedRequest(actionContext);
        }

        protected bool IsValidStaticApiKey(IEnumerable<string> tokenHeaders)
        {
            string cookieToken = "";
            string formToken = "";

            string[] tokens = tokenHeaders.First().Split(':');
            if (tokens.Length == 2)
            {
                cookieToken = tokens[0].Trim();
                formToken = tokens[1].Trim();
            }

            //Validate method throws an exception if the tokens are not valid.
            try
            {

                AntiForgery.Validate(cookieToken, formToken);
            }
            catch (Exception ex)
            {
                LogWriter.LogMessage("API Key Validation : " + ex.Message + ex.StackTrace);
                return false;
            }

            return true;
        }
    }
}