using System;
using System.Collections.Generic;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Threading;
using SqlDynamite.Common;

namespace SqlDynamite
{
    /// <summary>
    /// Interaction logic for ListWindow.xaml
    /// </summary>
    public partial class ListWindow
    {
        internal static readonly string ConfigFile;

        private string _connectionName;
        private string _serverType;
        private string _driver;
        private string _server;
        private string _database;
        private string _user;
        private string _password;
        private bool _sspi;
        private ConnectionType _connectionType;
        private string _newConnectionName;

        static ListWindow()
        {
            string appdata = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            if (!Directory.Exists(appdata + "\\SQL Dynamite"))
            {
                Directory.CreateDirectory(appdata + "\\SQL Dynamite");
            }
            ConfigFile = appdata + "\\SQL Dynamite\\SQL_Dynamite.xml";
        }

        public ListWindow()
        {
            InitializeComponent();
        }

        public string NewConnectionName => _newConnectionName;

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            ConfigWindow configWindow = new ConfigWindow {Owner = this, ShowInTaskbar = false};
            if (configWindow.ShowDialog().Value)
            {
                _connectionName = configWindow.ConnectionName.Text;
                _sspi = configWindow.SSPI.IsChecked.Value;
                _serverType = configWindow.ServerType.Text;
                _driver = configWindow.Driver.Text;
                _server = configWindow.Server.Text;
                _database = configWindow.Database.Text;
                _user = configWindow.User.Text;
                _password = configWindow.Password.Password;
                _connectionType = configWindow.GetConnectionType();
                ServerInfo serverInfo = new ServerInfo(_serverType, _driver, _server, _database, _user, _password,
                    _sspi.ToString(), _connectionType.ToString(), _connectionName);
                try
                {
                    XmlUtil.InsertConfig(ConfigFile, _connectionName, serverInfo);
                    FillConnections();
                    _newConnectionName = _connectionName;
                }
                catch (Exception exc)
                {
                    MessageBox.Show(exc.GetExceptionMessages());
                }
            }
        }

        private void button2_Click(object sender, RoutedEventArgs e)
        {
            if (Connections.SelectedIndex != -1)
            {
                string cnf = ((ListBoxItem) Connections.SelectedItem).Content.ToString();
                ServerInfo crs;
                try
                {
                    crs = XmlUtil.SelectConfig(ConfigFile, cnf);
                }
                catch (Exception exc)
                {
                    MessageBox.Show(exc.GetExceptionMessages());
                    return;
                }
                if (crs != null)
                {
                    ConfigWindow configWindow = new ConfigWindow
                    {
                        Owner = this,
                        ShowInTaskbar = false,
                        ConnectionName = {Text = cnf},
                        ServerType = {Text = crs.ServerType},
                        Driver = {Text = crs.Driver},
                        Server = {Text = crs.Server},
                        Database = {Text = crs.Database},
                        User = {Text = crs.User},
                        Password = {Password = crs.Password},
                        SSPI = {IsChecked = bool.Parse(crs.SSPI)},
                        ODBC = {IsChecked = crs.ConnectionType == "ODBC"},
                        OLEDB = {IsChecked = crs.ConnectionType == "OLEDB"}
                    };
                    if (configWindow.ShowDialog().Value)
                    {
                        _connectionName = configWindow.ConnectionName.Text;
                        _sspi = configWindow.SSPI.IsChecked.Value;
                        _serverType = configWindow.ServerType.Text;
                        _driver = configWindow.Driver.Text;
                        _server = configWindow.Server.Text;
                        _database = configWindow.Database.Text;
                        _user = configWindow.User.Text;
                        _password = configWindow.Password.Password;
                        _connectionType = configWindow.GetConnectionType();
                        ServerInfo serverInfo = new ServerInfo(_serverType, _driver, _server, _database, _user,
                            _password, _sspi.ToString(), _connectionType.ToString(), _connectionName);
                        try
                        {
                            XmlUtil.UpdateConfig(ConfigFile, cnf, _connectionName, serverInfo);
                            FillConnections();
                            _newConnectionName = _connectionName;
                        }
                        catch (Exception exc)
                        {
                            MessageBox.Show(exc.GetExceptionMessages());
                        }
                    }
                }
            }
        }

        private void button3_Click(object sender, RoutedEventArgs e)
        {
            if (Connections.SelectedIndex != -1)
            {
                MessageBoxResult mbr = MessageBox.Show("Do you want to delete this entry?", "Confirmation",
                    MessageBoxButton.YesNo, MessageBoxImage.Question);
                if (mbr == MessageBoxResult.Yes)
                {
                    try
                    {
                        XmlUtil.DeleteConfig(ConfigFile, ((ListBoxItem)Connections.SelectedItem).Content.ToString());
                        FillConnections();
                    }
                    catch (Exception exc)
                    {
                        MessageBox.Show(exc.GetExceptionMessages());
                    }
                }
            }
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            FillConnections();
            Dispatcher.Invoke(DispatcherPriority.Loaded, (Action) delegate { });
            if (Connections.Items.Count > 0)
            {
                Connections.SelectedIndex = 0;
            }
        }

        private void FillConnections()
        {
            Connections.Items.Clear();
            IEnumerable<Tuple<string, bool>> cns;
            try
            {
                cns = XmlUtil.SelectConfig(ConfigFile);
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.GetExceptionMessages());
                return;
            }
            foreach (Tuple<string, bool> cn in cns)
            {
                ListBoxItem item = new ListBoxItem {Content = cn.Item1};
                if (cn.Item2) item.Background = new SolidColorBrush(Colors.LightPink);
                Connections.Items.Add(item);
            }
        }

        private void button5_Click(object sender, RoutedEventArgs e)
        {
            if (Connections.SelectedIndex != -1)
            {
                try
                {
                    ListBoxItem cnf = (ListBoxItem)Connections.SelectedItem;
                    XmlUtil.MakeDefaultConfig(ConfigFile, cnf.Content.ToString());
                    FillConnections();
                }
                catch (Exception exc)
                {
                    MessageBox.Show(exc.GetExceptionMessages());
                }
            }
        }

        private void Connections_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            button2_Click(sender, null);
        }

        private void button4_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(_newConnectionName) && Connections.Items.Count > 0)
            {
                _newConnectionName = (Connections.Items[Connections.Items.Count - 1] as ListBoxItem).Content.ToString();
            }
        }
    }
}