using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
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 AesCryptography
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow() => InitializeComponent();

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if(string.IsNullOrEmpty(LineTextBox.Text))
            {
                MessageBox.Show("Строка для операции не заполнена", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }
            if (string.IsNullOrEmpty(KeyTextBox.Text))
            {
                MessageBox.Show("Ключ для операции не заполнен", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }

            var key = Encoding.UTF8.GetBytes(KeyTextBox.Text);
            var IV = new byte[16];
            string result = string.Empty;
            try
            {
                result = OperationComboBox.SelectedIndex == 0 ?
                Convert.ToBase64String(LineTextBox.Text.EncryptStringToBytesAes(key, IV)) :
                Convert.FromBase64String(LineTextBox.Text).DecryptStringFromBytesAes(key, IV);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            ResultStackPanel.Visibility = Visibility.Visible;
            ResultTextBox.Text = result;
            Clipboard.SetText(result);
            MessageBox.Show("Результат скопирован в буфер обмена", "Информация", MessageBoxButton.OK, MessageBoxImage.Information);
        }

        private void OperationComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if(ResultStackPanel?.Visibility == Visibility.Visible)
            {
                ResultStackPanel.Visibility = Visibility.Collapsed;
                LineTextBox.Text = string.Empty;
                ResultTextBox.Text = string.Empty;
            }
        }

        private void Window_Closed(object sender, EventArgs e) => Application.Current.Shutdown();
    }

    public static class AESExtension
    {
        public static byte[] EncryptStringToBytesAes(this string plainText, byte[] key, byte[] IV)
        {
            if (plainText == null || plainText.Length <= 0) throw new ArgumentNullException(nameof(plainText));
            if (key == null || key.Length <= 0) throw new ArgumentNullException(nameof(key));
            if (IV == null || IV.Length <= 0) throw new ArgumentNullException(nameof(IV));

            byte[] encrypted;

            using (Aes aesAlg = Aes.Create())
            {
                aesAlg.Key = key;
                aesAlg.IV = IV;

                ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg  .Key, aesAlg.IV);
                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                        {
                            swEncrypt.Write(plainText);
                        }
                        encrypted = msEncrypt.ToArray();
                    }
                }
            }
            return encrypted;
        }
        public static string DecryptStringFromBytesAes(this byte[] cipherText, byte[] key, byte[] IV)
        {
            if (cipherText == null || cipherText.Length <= 0) throw new ArgumentNullException(nameof(cipherText));
            if (key == null || key.Length <= 0) throw new ArgumentNullException(nameof(key));
            if (IV == null || IV.Length <= 0) throw new ArgumentNullException(nameof(IV));
            string plaintext = null;
            using (Aes aesAlg = Aes.Create())
            {
                aesAlg.Key = key;
                aesAlg.IV = IV;

                ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);

                using (MemoryStream msDecrypt = new MemoryStream(cipherText))
                {
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                        {
                            plaintext = srDecrypt.ReadToEnd();
                        }
                    }
                }
            }

            return plaintext;
        }
    }
}
