using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.ModelBinding;
using LHDN.CRM.BC.Common;

using LHDN.CRM.BC.Services;
using LHDN.CRM.Models.ViewModels;
using System.Transactions;

namespace LHDN.CRM.WebAPI.CallCentre.Controllers
{
    public class BaseApiController : ApiController
    {
        AuditService svcAudit = new AuditService();
        ErrorService svcError = new ErrorService();
        #region Audit Log

        public virtual void AuditLogTxn(AuditService.AuditEventID auditEventID,
            AuditService.ResultType resultType,
            AuditService.ActionType actionType,
            string userID,
            DateTime createdDate,
            string additionalInfo)
        {
            Task.Factory.StartNew(() =>
            {
                AuditLogTxn(auditEventID,
                resultType,
                actionType,
                userID,
                createdDate,
                additionalInfo, null, null);
            });
        }

        public virtual void AuditLogTxn(AuditService.AuditEventID auditEventID,
            AuditService.ResultType resultType,
            AuditService.ActionType actionType,
            string userID,
            DateTime createdDate,
            string additionalInfo,
            params AuditDetailViewModel[] auditEvents)
        {
            AuditLogTxn(auditEventID,
                resultType,
                actionType,
                userID,
                createdDate,
                additionalInfo,
                auditEvents.ToList());
        }

        public virtual void AuditLogTxn(AuditService.AuditEventID auditEventID,
            AuditService.ResultType resultType,
            AuditService.ActionType actionType,
            string userID,
            DateTime createdDate,
            string additionalInfo = null,
            List<AuditDetailViewModel> lstAuditDetails = null,
            string refTableName = null,
            long? refTableID = null)
        {
            //string creator = HttpContext.Current.User.Identity.Name == "" ? "SYSTEM" : HttpContext.Current.User.Identity.Name;

            Task.Factory.StartNew(() =>
            {
                using (var scope = new TransactionScope(TransactionScopeOption.Required))
                {
                    string creator = "SYSTEM";
                    svcAudit.SaveAudit((int)auditEventID,
                        resultType,
                        actionType,
                        userID == "" ? "SYSTEM" : userID,
                        creator,
                        createdDate,
                        additionalInfo,
                        lstAuditDetails,
                        refTableName,
                        refTableID);
                    scope.Complete();
                }
            });
        }

        #endregion

        #region Error Log
        public virtual void LogError(string message, string userId)
        {
            svcError.LogError(message, userId, "LHDN.CRM.WebAPI.External");
        }

        #endregion

        ////public override ExecuteAsync(HttpControllerContext controllerContext, CancellationToken cancellationToken)

        public async override Task<HttpResponseMessage> ExecuteAsync(HttpControllerContext controllerContext, CancellationToken cancellationToken)
        {

            var headers = controllerContext.Request.Headers;
            string _apikey = headers.GetValues("_apikey").FirstOrDefault();
            string _reqtimestamp = headers.GetValues("_reqtimestamp").FirstOrDefault();
            string secretKey = string.Empty;
            string sH = string.Empty;
            // Boolean valid = false;

            secretKey = Utilities.GetAppSetting("CRMWebApi.SecretKey") + _reqtimestamp;
            sH = SHA1(secretKey);

            if (sH != _apikey)
            {
                throw new UnauthorizedAccessException("Invalid API Key");
            }

            var response = await base.ExecuteAsync(controllerContext, cancellationToken);

            return response;
        }


        private string SHA1(string sIn)
        {
            System.Security.Cryptography.SHA1CryptoServiceProvider sha1Obj = new System.Security.Cryptography.SHA1CryptoServiceProvider();
            Byte[] bytesToHash = System.Text.Encoding.ASCII.GetBytes(sIn);
            string strResult = string.Empty;
            bytesToHash = sha1Obj.ComputeHash(bytesToHash);

            foreach (byte b in bytesToHash)
            {
                strResult += b.ToString("x2");
            }
            return strResult;
        }

    }
}