using LHDN.CRM.BC.Repositories;
using LHDN.CRM.Models.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Net.Http.Headers;
using System.Web;
using LHDN.CRM.BC.Services;
using LHDN.CRM.BC.Common;

namespace LHDN.CRM.WebAPI.Handlers
{
    public class UPTimeStampHandler : DelegatingHandler
    {
        private UserProfileService userSvc = new UserProfileService();
        protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {

            var response = await base.SendAsync(request, cancellationToken);
            var cookie = request.Headers.GetCookies("up_timestamp").FirstOrDefault();

           //if(cookie != null) Helper.LogMessage("User Cookie up_timestamp " + GetCookieValue(cookie, "up_timestamp"));
            //Helper.LogMessage("UPTimeStampHandler up_timestamp " + userSvc.DisplayName + " : " + userSvc.UPTimeStamp.ToString());
            if (cookie == null || (cookie!=null && !CompareValue(userSvc.UPTimeStamp, GetCookieValue(cookie, "up_timestamp"))))
            {
               // Helper.LogMessage("Updated Cookie time stamp");
                cookie = new CookieHeaderValue("up_timestamp", userSvc.UPTimeStamp)
                { HttpOnly = false, Secure = false, Path = "/" };
                response.Headers.AddCookies(new CookieHeaderValue[] { cookie });
            }
            return response;
        }

        private bool CompareValue (string strValue1, string strValue2)
        {
            bool blnSame = false;

            if (!string.IsNullOrEmpty(strValue1) && !string.IsNullOrEmpty(strValue2))
            {
                //Helper.LogMessage("UPTimeStampHandler up_timestamp before " + strValue1 + " " + strValue2);

                if (strValue1.Equals(strValue2))
                {
                    blnSame = true;
                    // Helper.LogMessage("User TimeStamp are different");
                }
            }
           
            return blnSame;
        }

        private string GetCookieValue(CookieHeaderValue cookie, string key)
        {
            string strValue = "";
            var obj = cookie.Cookies.AsEnumerable().Where(x=>x.Name == key).FirstOrDefault();
            if (obj != null) {
                strValue = obj.Value;
            }
            return strValue;
        }

    }
}