using ComPDFKitViewer.AnnotEvent;
using PDFSettings;
using PDFSettings.Settings;
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using System.Dynamic;
using System.Windows;
using System.IO;
using PDF_Office.Properties;
using PDF_Office;

namespace PDF_Office.Helper
{
    public class SettingHelper
    {
        public static void SortRecentOpenFiles(string filePath)
        {
            if (Settings.Default.RecentOpenFiles == null)
                Settings.Default.RecentOpenFiles = new RecentOpenFiles();

            OpenFileInfo existFile = null;
            foreach (var file in Settings.Default.RecentOpenFiles)
            {
                if (file.FilePath.ToLower() == filePath.ToLower())
                {
                    if(file.FilePath != filePath)
                    {
                        file.FilePath = filePath;
                        file.FileName = filePath.Substring(filePath.LastIndexOf("\\") + 1);
                    }

                    file.LastOpenTime = DateTime.Now;
                    existFile = file;
                    break;
                }
            }

            if (existFile != null)
            {
                if (Settings.Default.RecentOpenFiles.IndexOf(existFile) != 0)
                {
                    Settings.Default.RecentOpenFiles.Remove(existFile);
                    Settings.Default.RecentOpenFiles.Insert(0, existFile);
                }
            }
            else
            {
                OpenFileInfo fileInfo = new OpenFileInfo();
                fileInfo.FileName = filePath.Substring(filePath.LastIndexOf("\\") + 1);
                fileInfo.FilePath = filePath;
                fileInfo.ThumbImgPath = "";
                fileInfo.LastOpenTime = DateTime.Now;
                PDF_Office.Properties.Settings.Default.RecentOpenFiles.Insert(0, fileInfo);
            }
            Settings.Default.Save();
        }

        public static void RemoveRecentOpenFile(string filePath)
        {
            if (Settings.Default.RecentOpenFiles == null || Settings.Default.RecentOpenFiles.Count == 0)
                return;
               
            OpenFileInfo deleteItem = null;
            foreach(var item in Settings.Default.RecentOpenFiles)
            {
                if (item.FilePath.ToLower() == filePath.ToLower())
                {
                    deleteItem = item;
                    break;
                }
            }

            if(deleteItem!=null)
            {
                DeleteByPath(deleteItem.ThumbImgPath);
                Settings.Default.RecentOpenFiles.Remove(deleteItem);
                Settings.Default.Save();
            }
        }

        public static void DeleteByPath(string path)
        {
            try
            {
                if (!string.IsNullOrEmpty(path) && System.IO.File.Exists(path))
                    System.IO.File.Delete(path);
            }
            catch { }
        }

        public static void RemoveAllRecentOpenFiles()
        {
            if (Settings.Default.RecentOpenFiles == null || Settings.Default.RecentOpenFiles.Count == 0)
                return;

            string folderPath = System.IO.Path.Combine(App.CurrentPath, "CoverImage");
            DirectoryInfo directoryInfo = new DirectoryInfo(folderPath);
            if (directoryInfo.Exists)
            {
                var files = directoryInfo.GetFiles();
                foreach (var file in files)
                {
                    if (file.Exists)
                        file.Delete();
                }
            }

            Settings.Default.RecentOpenFiles.Clear();
            Settings.Default.Save();
        }

        public static OpenFileInfo GetFileInfo(string filePath)
        {
            if (Settings.Default.RecentOpenFiles == null || Settings.Default.RecentOpenFiles.Count == 0)
                return null;

            foreach(var info in Settings.Default.RecentOpenFiles)
            {
                if (info.FilePath == filePath)
                    return info;
            }
            return null;
        }

        public static void SetFileInfo(OpenFileInfo openFileInfo)
        {
            try
            {
                if (Settings.Default.RecentOpenFiles == null || Settings.Default.RecentOpenFiles.Count == 0 || openFileInfo == null)
                    return;

                for (int i = 0; i < Settings.Default.RecentOpenFiles.Count; i++)
                {
                    if (Settings.Default.RecentOpenFiles[i].FilePath == openFileInfo.FilePath)
                    {
                        Settings.Default.RecentOpenFiles[i] = openFileInfo;
                        Settings.Default.Save();//保存时有可能会文件被占用
                        return;
                    }
                }
            }
            catch { }
        }

        public static DefaultAnnotProperty GetAnnotDefaultProperty(AnnotArgsType annotToolType,string saveKey="")
        {
            //if (Settings.Default.DefautAnnotProperties != null)
            //{
            //    if(saveKey=="")
            //    {
            //        return Settings.Default.DefautAnnotProperties.GetAnnotProperty(annotToolType);
            //    }
            //    return Settings.Default.DefautAnnotProperties.GetAnnotProperty(annotToolType,saveKey);
            //}
            return null;
        }

        public static void SetAnnotDefaultProperty(DefaultAnnotProperty annotProperty)
        {
            //if (Settings.Default.DefautAnnotProperties == null)
            //{
            //    Settings.Default.DefautAnnotProperties = new DefaultAnnotProperties();
            //}
            //Settings.Default.DefautAnnotProperties.SetAnnotProperty(annotProperty);
            //Settings.Default.Save();
        }
        private static string KeyAlaphabet = "0123456789ABCDEFGHIGKLMNOPQRSTUVWXYZ";
        public static char NumberToChar(int num)
        {
            if (num >= 0 && num <= 35)
            {
                return KeyAlaphabet[num];
            }
            throw new ArgumentException("Wrong num value.", "ch");
        }
        /// <summary>
        /// AES加密
        /// </summary>
        /// <param name="text">加密字符</param>
        /// <param name="password">加密的密码</param>
        /// <returns></returns>
        public static string AESEncrypt(string text, string password)
        {
            RijndaelManaged rijndaelCipher = new RijndaelManaged();
            rijndaelCipher.Mode = CipherMode.CBC;
            rijndaelCipher.Padding = PaddingMode.PKCS7;
            rijndaelCipher.KeySize = 128;
            rijndaelCipher.BlockSize = 128;
            byte[] pwdBytes = Encoding.UTF8.GetBytes(password);
            byte[] keyBytes = new byte[16];
            int len = pwdBytes.Length;
            if (len > keyBytes.Length) len = keyBytes.Length;
            Array.Copy(pwdBytes, keyBytes, len);
            rijndaelCipher.Key = keyBytes;
            rijndaelCipher.IV = new byte[16];
            ICryptoTransform transform = rijndaelCipher.CreateEncryptor();
            byte[] plainText = Encoding.UTF8.GetBytes(text);
            byte[] cipherBytes = transform.TransformFinalBlock(plainText, 0, plainText.Length);
            return Convert.ToBase64String(cipherBytes);
        }
        /// <summary>
        /// AES解密
        /// </summary>
        /// <param name="text"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public static string AESDecrypt(string text, string password)
        {
            RijndaelManaged rijndaelCipher = new RijndaelManaged();
            rijndaelCipher.Mode = CipherMode.CBC;
            rijndaelCipher.Padding = PaddingMode.PKCS7;
            rijndaelCipher.KeySize = 128;
            rijndaelCipher.BlockSize = 128;
            byte[] encryptedData = Convert.FromBase64String(text);
            byte[] pwdBytes = Encoding.UTF8.GetBytes(password);
            byte[] keyBytes = new byte[16];
            int len = pwdBytes.Length;
            if (len > keyBytes.Length) len = keyBytes.Length;
            Array.Copy(pwdBytes, keyBytes, len);
            rijndaelCipher.Key = keyBytes;
            rijndaelCipher.IV = new byte[16];
            ICryptoTransform transform = rijndaelCipher.CreateDecryptor();
            byte[] plainText = transform.TransformFinalBlock(encryptedData, 0, encryptedData.Length);
            return Encoding.UTF8.GetString(plainText);
        }

        public static ProductActiveInfo GetProductActiveInfo()
        {
            //if (Settings.Default.ProductActiveStore != null)
            //{
            //    ProductActiveInfo activeInfo = new ProductActiveInfo();
            //    ProductActiveStore storeInfo= Settings.Default.ProductActiveStore;
            //    Random random = new Random((int)storeInfo.UpdateTime.Ticks);
            //    StringBuilder keyBuilder = new StringBuilder();
            //    for (int i = 0; i < 16; i++)
            //    {
            //        keyBuilder.Append(NumberToChar(random.Next(0, 35)));
            //    }
            //    string checkData = AESEncrypt(storeInfo.SignData, keyBuilder.ToString());
            //    MD5 mD5 = MD5.Create();
            //    byte[] hashCode = mD5.ComputeHash(Encoding.UTF8.GetBytes(checkData));
            //    StringBuilder checkBuilder = new StringBuilder();
            //    foreach (byte code in hashCode)
            //    {
            //        checkBuilder.Append(code.ToString("X2"));
            //    }
            //    if (checkBuilder.ToString() == storeInfo.CheckSum)
            //    {
            //        string decryptData = AESDecrypt(storeInfo.SignData, keyBuilder.ToString());
            //        activeInfo = JsonConvert.DeserializeObject<ProductActiveInfo>(decryptData);
            //    }
            //    return activeInfo;
            //}
            return null;
        }
        public static void SetProductActiveStore(ProductActiveInfo activeInfo)
        {
            //ProductActiveStore activeStore = new ProductActiveStore();
            //activeStore.UpdateTime = DateTime.Now;
            //string rawData = JsonConvert.SerializeObject(activeInfo);
            //Random random = new Random((int)activeStore.UpdateTime.Ticks);
            //StringBuilder keyBuilder = new StringBuilder();
            //for (int i = 0; i < 16; i++)
            //{
            //    keyBuilder.Append(NumberToChar(random.Next(0, 35)));
            //}
            //activeStore.SignData = AESEncrypt(rawData, keyBuilder.ToString());
            //string checkData = AESEncrypt(activeStore.SignData, keyBuilder.ToString());
            //MD5 mD5 = MD5.Create();
            //byte[] hashCode = mD5.ComputeHash(Encoding.UTF8.GetBytes(checkData));
            //StringBuilder checkBuilder = new StringBuilder();
            //foreach(byte code in hashCode)
            //{
            //    checkBuilder.Append(code.ToString("X2"));
            //}
            //activeStore.CheckSum = checkBuilder.ToString();
            //Settings.Default.ProductActiveStore = activeStore;
            //Settings.Default.Save();
        }
    }
}
