using Microsoft.IdentityModel.JsonWebTokens;
using PCUT.Entities;
using System;

namespace Http.Core.Contexts
{
    public class UserContext : IDisposable
    {
        private UserContext() { }
        private static readonly object _instanceLock = new object();
        private static UserContext _instance;
        public static UserContext Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (_instanceLock)
                    {
                        if (_instance == null)
                            _instance = new UserContext();
                    }
                }
                return _instance;
            }
        }

        public bool DebugFeaturesEnabled { get; set; } = false;

        public UserProfile Profile { get; private set; }
        public string AccessToken { get; private set; }
        public string RefreshToken { get; private set; }
        public DateTime? ExpiredTime { get; private set; }
        public string DeviceId { get; private set; }
        public string AppVersion { get; private set; }

        public bool IsPermittedEdit => Profile.Role == "admin" || (Profile.IsPermittedEdit ?? false);

        public void SetDeviceId(string deviceId)
        {
            if (DeviceId == null)
            {
                DeviceId = deviceId;
            }
        }

        public void SetAppVersion(string appVersion)
        {
            if (AppVersion == null)
            {
                AppVersion = appVersion;
            }
        }

        private readonly object _updateLock = new object();
        internal void SetValue(string accessToken, string refreshToken, string userName = null)
        {
            lock(_updateLock)
            {
                AccessToken = accessToken;
                RefreshToken = refreshToken;
                try
                {
                    var token = new JsonWebToken(AccessToken);
                    ExpiredTime = token.ValidTo != DateTime.MinValue ? token.ValidTo : (DateTime?)null;
                }
                catch { }
            }
        }

        internal void SetProfile(UserProfile profile)
        {
            Profile = profile;
        }

        public void Dispose()
        {
            AccessToken = null;
            RefreshToken = null;
            DeviceId = null;
            ExpiredTime = null;
            Profile = null;
            _instance = null;
        }
    }
}
