using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using JWT.Algorithms;
using JWT.Builder;
using JWT.Serializers;

namespace BLL.Services.System
{
    public class TokenData
    {
        public int ID { set; get; }
        public DateTime ValidTime { set; get; }

        public bool IsValid => ValidTime >= DateTime.Now;
        public long ValidTime_Bin
        {
            set => ValidTime = DateTime.FromBinary(value);
            get => ValidTime.ToBinary();
        }
    }

    public class TokenServices
    {
        private const string Key = "GQDstcKsx0NHjPOuXOYg5MbeJ1XT0uFiwDVvVBrk";


        public string CreateTocken(TokenData data)
        {
            return new JwtBuilder()
                .WithAlgorithm(new HMACSHA256Algorithm())
                .WithSecret(Key)
                .AddClaim("ID", data.ID)
                .AddClaim("ValidTime", data.ValidTime_Bin)
                .Build();
        }
        public string CreateTocken(int ID, TimeSpan LiveTime)
        {
            return CreateTocken(new TokenData()
            {
                ID = ID,
                ValidTime = DateTime.Now + LiveTime
            });
        }

        public TokenData GetData(string token)
        {
            var data = new JwtBuilder()
                .WithSecret(Key)
                .MustVerifySignature()
                .Decode<IDictionary<string, object>>(token);

            return new TokenData()
            {
                ID = (int)(long)data["ID"],
                ValidTime_Bin = (long)data["ValidTime"]
            };
        }
    }
}
