using MahApps.Metro.Controls;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Text.RegularExpressions;
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.Shapes;
using Windows.System;

namespace ZKuP
{
    /// <summary>
    /// Interaktionslogik für FamilyBooking.xaml
    /// </summary>
    public partial class FamilyBooking : MetroWindow
    {
        DateTime date = DateTime.MinValue;
        int slot = 0;
        public FamilyBooking(int Slot, DateTime Date)
        {
            InitializeComponent();

            date = Date;
            slot = Slot;

            string time = "";
            switch (Slot)
            {
                case 1:
                    time = "14:00 - 16:00";
                    break;
                case 2:
                    time = "16:15 - 17:45";
                    break;
                case 3:
                    time = "18:00 - 19:30";
                    break;
                default:
                    time = "Error";
                    break;
            }

            lblDate.Text = $"am {date.ToString("dddd", new CultureInfo("de-DE"))} den {date.Date.ToString("dd.MM.yy")} {time}";
        }

        private async void btnBook_Click(object sender, RoutedEventArgs e)
        {
            if (CheckButtons())
            {
                var count = SQL.ReadSingleValue($"SELECT COUNT(`Date`) FROM {MainWindow.table}.family WHERE `Date` = '{date.ToString("yyyy-MM-dd")}'");

                if (int.Parse(count) < 3)
                {
                    try
                    {
                        //await SQL.WriteSQL($"INSERT INTO {MainWindow.table}.family (Name, TelNr, Persnr, AnzBegleiter, Date, Slot, User, Email) VALUES ('{tbName.Text}','{tbTel.Text}','{tbPersnr.Text}','{tbAnzBegleiter.Text}','{date.ToString("yyyy-MM-dd")}','{slot}','{Environment.UserName}','{tbEmail.Text}')");

                        await SQL.CreateAndWriteSQL($"INSERT INTO {MainWindow.table}.family (Name, TelNr, Persnr, AnzBegleiter, Date, Slot, User, Email) VALUES (@Name,@TelNr,@Persnr,@AnzBegleiter,@Date,@Slot,@User,@Email)", new List<MySql.Data.MySqlClient.MySqlParameter>()
                        {
                            new MySql.Data.MySqlClient.MySqlParameter("@Name",tbName.Text),
                            new MySql.Data.MySqlClient.MySqlParameter("@TelNr",tbTel.Text),
                            new MySql.Data.MySqlClient.MySqlParameter("@Persnr",tbPersnr.Text),
                            new MySql.Data.MySqlClient.MySqlParameter("@AnzBegleiter",tbAnzBegleiter.Text),
                            new MySql.Data.MySqlClient.MySqlParameter("@Date",date.ToString("yyyy-MM-dd")),
                            new MySql.Data.MySqlClient.MySqlParameter("@Slot",slot),
                            new MySql.Data.MySqlClient.MySqlParameter("@User",Environment.UserName),
                            new MySql.Data.MySqlClient.MySqlParameter("@Email",tbEmail.Text)
                        });
                                                                        
                        await SQL.CreateAndWriteSQL($"UPDATE {MainWindow.table}.changes SET timestamp = @time WHERE idchanges = '4'", new List<MySql.Data.MySqlClient.MySqlParameter>()
                        {
                            new MySql.Data.MySqlClient.MySqlParameter("@time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"))
                        });
                    }
                    catch (Exception)
                    {
                        MessageBox.Show("Es ist ein Fehler aufgetreten", "Fehler", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                    finally
                    {
                        MessageBox.Show("Werksführung wurde erfolgreich gebucht!", "Erfolgreich", MessageBoxButton.OK, MessageBoxImage.Information);
                        this.Close();
                    }
                }
                else
                {
                    MessageBox.Show("Tag ist bereits vollständig ausgebucht", "Kein freier Slot", MessageBoxButton.OK, MessageBoxImage.Error);
                    this.Close();
                }
            }
            else
                MessageBox.Show("Alle Felder müssen korrekt ausgefüllt werden!", "Fehlende Felder", MessageBoxButton.OK, MessageBoxImage.Error);
        }

        private bool CheckButtons()
        {
            var ret = false;
            if (Helper.FindVisualChildren<TextBox>(this).Any(p => string.IsNullOrWhiteSpace(p.Text)))
                ret = false;
            else ret = true;

            try
            {
                var address = new MailAddress(tbEmail.Text).Address;
                ret = true;
            }
            catch (FormatException)
            {
                ret = false;
            }

            return ret;
        }

        ToolTip tt = new ToolTip();
        private void tbAnzBegleiter_TextChanged(object sender, TextChangedEventArgs e)
        {
            tt.IsOpen = false;

            if (Regex.IsMatch(tbAnzBegleiter.Text, "[0-9]"))
            {
                if (tbAnzBegleiter.Text.Length > 1)
                {
                    e.Handled = true;
                    tbAnzBegleiter.Text = tbAnzBegleiter.Text.Remove(tbAnzBegleiter.Text.Length - 1, 1);
                }

                if (int.Parse(tbAnzBegleiter.Text) > 5)
                {
                    tt.Content = "Maximal 5 Personen";

                    tbAnzBegleiter.ToolTip = tt;

                    tbAnzBegleiter.Text = "5";
                    tt.IsOpen = true;
                }
            }
            else
            {               
                tt.Content = "Ungültige Eingabe!";

                tbAnzBegleiter.ToolTip = tt;

                tbAnzBegleiter.Text = "5";
                tt.IsOpen = true;
            }
        }

        private void tbPersnr_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            if (Regex.IsMatch(e.Text, "[0-9]"))
            {
                e.Handled = false;
            }
            else e.Handled = true;
        }

        private void tb_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key != Key.OemComma)
            {
                e.Handled = false;
                return;
            }
            else
            {
                MessageBox.Show(this, "Komma (',') ist ein nicht erlaubtes Zeichen", "Achtung", MessageBoxButton.OK, MessageBoxImage.Information);
                e.Handled = true;
            }
            return;
        }



        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            Helper.CheckWindowIsInScreenSpace(this);
        }

        private void Window_LocationChanged(object sender, EventArgs e)
        {
            Helper.CheckWindowIsInScreenSpace(this);
        }
    }
}
