using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography;
using System.IO;

namespace Pilz.Cryptography
{
    public class SimpleStringCrypter : ICrypter
    {
        private TripleDES TripleDes;
        public Encoding TextEncoding { get; private set; } = Encoding.Default;

        public SimpleStringCrypter() : this(string.Empty)
        {
        }

        public SimpleStringCrypter(string key) : this(key, Encoding.Default)
        {
        }

        public SimpleStringCrypter(string key, Encoding textEncoding)
        {
            TextEncoding = textEncoding;
            TripleDes = TripleDES.Create();
            TripleDes.Key = TruncateHash(key,TripleDes.KeySize / 8);
            TripleDes.IV = TruncateHash(string.Empty, TripleDes.BlockSize / 8);
        }

        private byte[] TruncateHash(string key, int length)
        {
            SHA1 sha1CryptoServiceProvider = SHA1.Create();
            byte[] bytes = TextEncoding.GetBytes(key);
            byte[] array = sha1CryptoServiceProvider.ComputeHash(bytes);

            var output = new byte[length];
            var lowerLength = Math.Min(array.Length, output.Length);
            
            for (int i = 0; i < lowerLength; i++)
                output[i] = array[i];

            return output;
        }

        private string EncryptData(string plaintext)
        {
            byte[] bytes = TextEncoding.GetBytes(plaintext);
            MemoryStream memoryStream = new MemoryStream();
            CryptoStream cryptoStream = new CryptoStream(memoryStream, TripleDes.CreateEncryptor(), CryptoStreamMode.Write);
            cryptoStream.Write(bytes, 0, bytes.Length);
            cryptoStream.FlushFinalBlock();
            return Convert.ToBase64String(memoryStream.ToArray());
        }

        private string DecryptData(string encryptedtext)
        {
            byte[] array = Convert.FromBase64String(encryptedtext);
            MemoryStream memoryStream = new MemoryStream();
            CryptoStream cryptoStream = new CryptoStream(memoryStream, TripleDes.CreateDecryptor(), CryptoStreamMode.Write);
            cryptoStream.Write(array, 0, array.Length);
            cryptoStream.FlushFinalBlock();
            return TextEncoding.GetString(memoryStream.ToArray());
        }

        public string Encrypt(string plainValue)
        {
            return EncryptData(plainValue ?? string.Empty);
        }

        public string Decrypt(string encryptedValue)
        {
            if (string.IsNullOrEmpty(encryptedValue))
                return string.Empty;
            else
                return DecryptData(encryptedValue);
        }
    }
}
