using Gremlin.GremlinData.DBClasses;
using Microsoft.Win32;
using System.Windows;

namespace Gremlin.GremlinUI
{
    public partial class ChooseDB : Window
    {
        public ChooseDB()
        {
            InitializeComponent();

            tbServer.Text = Properties.Settings.Default.server;
            tbDatabase.Text = Properties.Settings.Default.database;
            tbUser.Text = Properties.Settings.Default.user;
            cbSslMode.Text = Properties.Settings.Default.SslMode;
            tbSslCa.Text = Properties.Settings.Default.SslCA;

            tbPort.Text = Properties.Settings.Default.port == 0 ? Properties.Settings.Default.port.ToString() : "3308";

            tbPassword.Password = Encryption.ToInsecureString(Encryption.DecryptString(Properties.Settings.Default.password));
        }

        private void BtnSave_Click(object sender, RoutedEventArgs e)
        {
            Properties.Settings.Default.server = tbServer.Text;
            Properties.Settings.Default.database = tbDatabase.Text;
            Properties.Settings.Default.user = tbUser.Text;
            Properties.Settings.Default.SslMode = cbSslMode.Text;
            Properties.Settings.Default.SslCA = tbSslCa.Text;

            Properties.Settings.Default.port = int.TryParse(tbPort.Text, out int port) ? port : 3306;

            Properties.Settings.Default.password = Encryption.EncryptString(Encryption.ToSecureString(tbPassword.Password));

            Properties.Settings.Default.Save();
            DialogResult = true;
            Close();
        }

        private void BtnCancel_Click(object sender, RoutedEventArgs e)
        {

        }

        private void BtnTest_Click(object sender, RoutedEventArgs e)
        {
            string connectionString = $"Server={tbServer.Text};Port={tbPort.Text};Database={tbDatabase.Text};Uid={tbUser.Text};Pwd={tbPassword.Password};SslMode={cbSslMode.Text};SslCa={tbSslCa.Text}";
            if (DbHelper.CheckDatabaseConnection(connectionString))
            {
                _ = MessageBox.Show($"Verbindung erfolgreich hergestellt.", "Success", MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }

        private void ButChooseCert_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog chooseCert = new() { DefaultExt = ".pem", Filter = "Zertifikate (*.pem)|*.pem" };
            if ((bool)chooseCert.ShowDialog())
            {
                tbSslCa.Text = chooseCert.FileName;
            }
        }
    }
}
