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

namespace Quadarax.Foundation.Common.Security
{
    public static class Secure
    {
        /*
        static string _passwordHash = "/:-s*oQ9VG~!]}))ud?ar*(5RanaWm{LHO-7Ncr[lvXGhB0=./raTYVGhO)n$ioE:tH1-TV.h57J+V-K+nVONHvAGeFa+0;R,`LUzqG&KI%-JQO6x>_/L'[sP2Cuz{z?9ch<2F~Cw@}@LNMpmv'viP+YHb}Z%.#dT*`5:nabn5n;8g1Tm<@,Zk(F9m{[s17*lc*P^}}HD,Mh]wnwaZfvYA`uCQ)Or&~cLy6wlYd_fw?ljr5i]l!UFhC'[sTbOaru";
        static string _saltKey =      "Unx.Y16ju9K)!@uA>9#DVxan%Wr,&c~[2q?T}Q'~XBweCgtvL7+&zv%(9uQxn#gnDYE_(IgQ%sUK-!n+{d-{vBhLXXbUJ$G]SQiXt.#S(WS=oQPTYU|%{o)fN=90/KgYfo&5$&hL}JAu8.+2]kPoRM1Rr&=prDKBpahWjjr?q;.`_8hrjJ]Y-ap88N$FcR,%SkyV)(ssdg1~A&3i?|n`yoJPBMy$];Q=%3b/^}|6<Dj!Agna3K;27gCl2Y9*vhqH";
        static string _vIKey =        "29T|l'6$&Z}(NpQ8]~d1U-kVO@ot8)&w$uf&UsDBKfcB_1rQ0'5H+w.EHKlS5)14AiBa(Kg4dmOpfan0s%eGwxy$1:|lRrkBLZJndV/l3;`W(Plx[n88TD]'kk@wYl_dA7#DP2|]V03~mkRh!8{$&bUTF585Zjb@B}d'2jo7n:7VA-e|X!nf7e$xP`dBh`DAE=Q~_TOVH;gJDK}Q>f@q.u&#2yOK=!F,$/{F5BxGvqUt$?ry0AmKNOH:y}XJq_x_";
        */
        private static string _passwordHash = "Vk&G#lG}vv@5S55x";
        private static string _saltKey = "vzb4[}[L%<='(U!n";
        private static string _vIKey = "&C%:gIt<P-|%nA45";


        public static void SetProperties(string passwordHash, string saltKey, string vIKey)
        {
            if (passwordHash.Length != 16)
                throw new ArgumentOutOfRangeException(nameof(passwordHash),"Value must have 16 chars.");

            if (saltKey.Length != 16)
                throw new ArgumentOutOfRangeException(nameof(saltKey),"Value must have 16 chars.");

            if (vIKey.Length != 16)
                throw new ArgumentOutOfRangeException(nameof(vIKey),"Value must have 16 chars.");


            _passwordHash = passwordHash;
            _saltKey = saltKey;
            _vIKey = vIKey;
        }

        public static string Encrypt(string plainText)
        {
            if (string.IsNullOrEmpty(plainText))
                return string.Empty;

            var plainTextBytes = Encoding.UTF8.GetBytes(plainText);

            var keyBytes = new Rfc2898DeriveBytes(_passwordHash, Encoding.UTF8.GetBytes(_saltKey)).GetBytes(256/8);
            var symmetricKey = new RijndaelManaged() { Mode = CipherMode.CBC, Padding = PaddingMode.Zeros};
            var encryptor = symmetricKey.CreateEncryptor(keyBytes, Encoding.ASCII.GetBytes(_vIKey));
			
            byte[] cipherTextBytes;

            using (var memoryStream = new MemoryStream())
            {
                using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                {
                    cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                    cryptoStream.FlushFinalBlock();
                    cipherTextBytes = memoryStream.ToArray();
                    cryptoStream.Close();
                }
                memoryStream.Close();
            }
            return Convert.ToBase64String(cipherTextBytes);
        }

        public static string Decrypt(string encryptedText)
        {
            if (string.IsNullOrEmpty(encryptedText))
                return string.Empty;

            var cipherTextBytes = Convert.FromBase64String(encryptedText);
            var keyBytes = new Rfc2898DeriveBytes(_passwordHash, Encoding.ASCII.GetBytes(_saltKey)).GetBytes(256 / 8);
            var symmetricKey = new RijndaelManaged() { Mode = CipherMode.CBC, Padding = PaddingMode.None };

            var decryptor = symmetricKey.CreateDecryptor(keyBytes, Encoding.ASCII.GetBytes(_vIKey));
            var memoryStream = new MemoryStream(cipherTextBytes);
            var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
            byte[] plainTextBytes = new byte[cipherTextBytes.Length];

            int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
            memoryStream.Close();
            cryptoStream.Close();
            return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount).TrimEnd("\0".ToCharArray());
        }
    }
}
