using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using XC.RSAUtil;

namespace Performance.Api
{
    public class LimitInformation
    {
        public DateTime ExpirationTime { get; set; }
        public string Remark { get; internal set; }
    }
    public class FunctionLimit
    {
        public static LimitInformation Limit { get; } = new LimitInformation();
        public static void Init(NLog.Logger logger)
        {
            string message = "此网站的验证证书有问题，验证证书已过期或还未生效，请及时联系供应厂商进行维护升级。";
            var filePath = Path.Combine(Environment.CurrentDirectory, "secret.key");
            logger.Info(filePath);
            if (!File.Exists(filePath))
            {
                Limit.ExpirationTime = DateTime.MinValue;
                Limit.Remark = message;
                return;
            }
            string content = ReadLimitContent(filePath, logger);
            logger.Info(content);
            if (string.IsNullOrEmpty(content))
            {
                Limit.ExpirationTime = DateTime.MinValue;
                Limit.Remark = message;
                return;
            }
            var timestamp = ConvertToExpiration(content);
            if (timestamp == 0)
            {
                Limit.ExpirationTime = DateTime.MinValue;
                Limit.Remark = message;
                return;
            }

            Limit.ExpirationTime = (new DateTime(1970, 1, 1, 8, 0, 0, DateTimeKind.Unspecified)).AddSeconds(timestamp);
            Limit.Remark = Limit.ExpirationTime > DateTime.Now ? "已授权开放使用！" : message;
        }

        private static long ConvertToExpiration(string content)
        {
            long result = 0;
            try
            {
                var bigDataRsa = new RsaPkcs8Util(Encoding.UTF8, "", privateKey, 2048);
                var timestamp = bigDataRsa.DecryptBigData(content, RSAEncryptionPadding.Pkcs1);
                long.TryParse(timestamp, out result);
                return result;
            }
            catch (Exception) { }
            return result;
        }

        private static string ReadLimitContent(string filePath, NLog.Logger logger)
        {
            var content = "";
            try
            {
                using (FileStream stream = new FileStream(filePath, FileMode.Open))
                using (StreamReader reader = new StreamReader(stream))
                {
                    content = reader.ReadToEnd();
                }
            }
            catch (Exception ex) { logger.Error(ex); }
            return content;
        }

        private static string privateKey = @"-----BEGIN PRIVATE KEY-----
MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQC/XTloNsKshhr/
GC34GSQq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