namespace AndroidApi.Models.Repository
{
    public class TokenRepository : ITokenRepository
    {
        private static string connectionString = string.Empty;
        private static string tokenKey = string.Empty;

        private readonly IAccountRepository _repository;

        public TokenRepository()
        {
            _repository = new AccountRepository();

            if (!string.IsNullOrWhiteSpace(ConfigurationManager.AppSettings["appctxt"]))
                connectionString = ConfigurationManager.AppSettings["appctxt"];

            if (!string.IsNullOrWhiteSpace(ConfigurationManager.AppSettings["tokenPrivateKey"]))
                tokenKey = ConfigurationManager.AppSettings["tokenPrivateKey"];
        }

        public TokenViewModel GenerateToken(AccountViewModel item)
        {
            TokenViewModel result = new TokenViewModel();

            var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tokenKey));
            var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature);
            var header = new JwtHeader(credentials);

            var payload = new JwtPayload
            {
                { "cus", item.UserId},
                { "timestamp", DateTime.Now},
            };

            var secToken = new JwtSecurityToken(header, payload);
            var handler = new JwtSecurityTokenHandler();

            result.Token = handler.WriteToken(secToken);
            result.StatusCode = 200;
            result.Message = "OK";

            return result;
        }

        public AccountViewModel ValidToken(string token)
        {
            AccountViewModel result = new AccountViewModel();
            int userId = 0;
            string timeStamp = string.Empty;

            var handler = new JwtSecurityTokenHandler();
            var tokenS = handler.ReadToken(token) as JwtSecurityToken;
            foreach (var items in tokenS.Claims)
            {
                if (items.Type == "cus")
                    int.TryParse(items.Value, out userId);

                if (items.Type == "timestamp")
                   timeStamp = items.Value;
            }

            if (IsTimeValid(timeStamp))
            {
                result = _repository.GetByUserId(userId);
            }

            return result;
        }

        private bool IsTimeValid(string timeStamp)
        {
            if (string.IsNullOrEmpty(timeStamp))
            {
                return false;
            }

            DateTime oDate = Convert.ToDateTime(timeStamp.Replace("\"", string.Empty));
            if (oDate < DateTime.Today)
            {
                return false;
            }

            return true;
        }
    }
}