using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace RegisterTool
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        // 嵌入私钥
        //private const string PrivateKey = @"<RSAKeyValue><Modulus>...</Modulus><Exponent>...</Exponent><P>...</P><Q>...</Q><DP>...</DP><DQ>...</DQ><InverseQ>...</InverseQ><D>...</D></RSAKeyValue>";

        public MainWindow()
        {
            InitializeComponent();
        }

        private void GenerateLicense_Click(object sender, RoutedEventArgs e)
        {
            // 获取用户输入的硬件码
            string machineCode = MachineCodeTextBox.Text.Trim();

            if (string.IsNullOrEmpty(machineCode))
            {
                MessageBox.Show("请输入有效的硬件码！");
                return;
            }

            // 检查用户选择的激活类型
            bool isPermanent = PermanentLicenseRadio.IsChecked == true;

            try
            {
                // 从嵌入的资源中读取私钥
                string privateKey = GetPrivateKeyFromResource();

                // 生成注册码
                string license = GenerateLicense(machineCode, isPermanent, privateKey);

                //加密license
                license = AesEncryptionHelper.EncryptString(license, AesEncryptionHelper.key);

                //license = AesEncryptionHelper.DecryptString(license, AesEncryptionHelper.key);

                // 显示生成的注册码
                LicenseTextBox.Text = license;
            }
            catch (Exception ex)
            {
                MessageBox.Show("生成注册码时出错: " + ex.Message);
            }
        }

        private string GenerateLicense(string machineCode, bool isPermanent,string privateKey)
        {
            // 创建许可证数据
            var licenseData = new
            {
                MachineCode = machineCode,
                ExpirationDate = isPermanent ? "9999-12-31" : DateTime.Now.AddMonths(2).ToString("yyyy-MM-dd")
            };

            // 将许可证数据序列化为 JSON 字符串
            string jsonData = JsonConvert.SerializeObject(licenseData);

            // 使用私钥对 JSON 数据进行签名
            using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
            {
                rsa.FromXmlString(privateKey);

                // 对 JSON 数据进行签名
                byte[] dataToSign = Encoding.UTF8.GetBytes(jsonData);
                byte[] signature = rsa.SignData(dataToSign, CryptoConfig.MapNameToOID("SHA256"));

                // 将签名转换为 Base64 字符串
                return Convert.ToBase64String(signature) + "::" + jsonData;
            }
        }

        private string GetPrivateKeyFromResource()
        {
            // 获取当前程序集
            Assembly assembly = Assembly.GetExecutingAssembly();

            // 列出所有嵌入的资源名称
            foreach (string resourceName1 in assembly.GetManifestResourceNames())
            {
                Console.WriteLine(resourceName1);
            }

            // 获取资源名称
            string resourceName = "RegisterTool.private_key.xml"; // 注意命名空间和文件名

            // 读取嵌入的资源文件
            using (Stream stream = assembly.GetManifestResourceStream(resourceName))
            {
                if (stream == null)
                    throw new FileNotFoundException("无法找到私钥资源文件");

                using (StreamReader reader = new StreamReader(stream))
                {
                    return reader.ReadToEnd();
                }
            }
        }
        //----------------------------------------------
    }
}
