using MahApps.Metro.Controls;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.RightsManagement;
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.Shapes;

namespace ZKuP
{
    /// <summary>
    /// Interaktionslogik für AddVisitorsList.xaml
    /// </summary>
    public partial class AddFirmenList : MetroWindow
    {
        public int GroupID { get; private set; }
        int width = 0;
        bool _isEdit = false;
        int _idFirmen = 0;

        public string Personen { get; set; }
        public string TelNr { get; set; }

        public AddFirmenList(bool isEdit = false, int idFirmen = 0, int PeopleCount = 0)
        {
            InitializeComponent();


            if (isEdit)
            {
                _isEdit = isEdit;
                _idFirmen = idFirmen;
                btnAdd.Visibility = Visibility.Visible;

                BuildWindow(PeopleCount);

                var list = SQL.ReadSingleValue($"SELECT Personen FROM {MainWindow.table}.firmenPeople WHERE idFirmen = '{_idFirmen}'").Split(';');

                if (list.Length > 0)
                {
                    var boxes = Helper.FindVisualChildren<TextBox>(spGroupPers).Where(p => p.Tag.ToString() == "Name").ToList();

                    for (var i = 0; i < boxes.Count(); i++)
                    {
                        if (list.Length > i && !string.IsNullOrWhiteSpace(list[i]))
                        {
                            if (boxes[i].Tag.ToString() == "Name")
                                boxes[i].Text = list[i];
                        }
                    }

                    boxes = Helper.FindVisualChildren<TextBox>(spGroupPers).Where(p => p.Tag.ToString() == "Tel").ToList();

                    list = SQL.ReadSingleValue($"SELECT TelNr FROM {MainWindow.table}.firmenPeople WHERE idFirmen = '{_idFirmen}'").Split(';');

                    for (var i = 0; i < boxes.Count(); i++)
                    {
                        if (list.Length > i && !string.IsNullOrWhiteSpace(list[i]))
                        {
                            if (boxes[i].Tag.ToString() == "Tel")
                                boxes[i].Text = list[i];
                        }
                    }
                }
            }
            else
            {
                if(PeopleCount > 0)
                {
                    for (var i = 0; i < PeopleCount; i++)
                        Add();
                }
            }
        }

        private void BuildWindow(int besucherAnzahl)
        {
            //int maxProSpalte = 10;    // Maximale Anzahl an Textfeldern pro Spalte

            // PanelsContainer soll die WrapPanels halten
            spGroupPers.Children.Clear();  // Vorherige Panels entfernen (falls schon welche existieren)

            // Erstelle die WrapPanels und füge sie dem StackPanel hinzu
            int columnCount = 2;// (int)Math.Ceiling((double)besucherAnzahl / maxProSpalte);

            //for (int i = 0; i < columnCount; i++)
            //{
            WrapPanel wrapPanel = new WrapPanel()
            {
                //Orientation = Orientation.Vertical,  // Jedes WrapPanel wird vertikal sein
                Margin = new Thickness(10),
                Width = 600
            };

            // Für jedes WrapPanel Textfelder hinzufügen
            for (int j = 0; j < besucherAnzahl; j++)
            {
                var mainPanel = new StackPanel();
                mainPanel.Orientation = Orientation.Horizontal;

                var sp = new StackPanel();
                var lbl = new TextBlock() { Text = $"Begleitperson Nr. {j + 1}:", Margin = new Thickness(5), Height = 20 };
                lbl.SetResourceReference(Control.ForegroundProperty, SystemColors.ControlTextBrushKey);
                sp.Children.Add(lbl);
                var tb = new TextBox() { Tag = "Name", Margin = new Thickness(10, 0, 10, 0), Height = 30, Width = 280, ToolTip = "Um eine Person zu entfernen, Feld leer lassen" };
                ToolTipService.SetInitialShowDelay(tb, 200);
                MahApps.Metro.Controls.TextBoxHelper.SetWatermark(tb, "Vorname Nachname");
                sp.Children.Add(tb);

                var sp2 = new StackPanel();
                var lbl2 = new TextBlock() { Text = $"", Margin = new Thickness(5), Height = 20 };
                lbl2.SetResourceReference(Control.ForegroundProperty, SystemColors.ControlTextBrushKey);
                sp2.Children.Add(lbl2);
                var tb2 = new TextBox() { Tag = "Tel", Margin = new Thickness(10, 0, 10, 0), Height = 30, Width = 280, ToolTip = "Um eine Person zu entfernen, Feld leer lassen" };
                ToolTipService.SetInitialShowDelay(tb2, 200);
                MahApps.Metro.Controls.TextBoxHelper.SetWatermark(tb2, "Telefonnummer");
                sp2.Children.Add(tb2);

                mainPanel.Children.Add(sp);
                mainPanel.Children.Add(sp2);

                wrapPanel.Children.Add(mainPanel);
            }

            // Das WrapPanel zum StackPanel hinzufügen
            spGroupPers.Children.Add(wrapPanel);
            //}

            width = (columnCount * 320) + 10;
            //this.Height = this.MinHeight + (besucherAnzahl * 80);
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            this.Height = spGroupPers.DesiredSize.Height + 80;
            this.Width = width;

            Helper.CheckWindowIsInScreenSpace(this);
        }

        private async void btnSend_Click(object sender, RoutedEventArgs e)
        {
            //await SendIt();
            this.Close();
        }

        private async Task SendIt()
        {
            var textBoxes = Helper.FindVisualChildren<TextBox>(spGroupPers);
            var person = "";

            foreach (var textBox in textBoxes)
            {
                if (textBox.Tag != null && (!string.IsNullOrWhiteSpace(textBox.Text) && textBox.Tag.ToString() == "Name")) person = textBox.Text;
                else if (textBox.Tag == null) return;
                //else if (string.IsNullOrWhiteSpace(textBox.Text))
                //{
                //    MessageBox.Show("Namensfeld muss ausgefüllt werden", "Fehlende Daten", MessageBoxButton.OK, MessageBoxImage.Error);
                //    return;
                //}

                if (textBox.Tag != null && textBox.Tag.ToString() == "Tel")
                {
                    //if(!string.IsNullOrWhiteSpace(textBox.Text))
                    //{
                    //    MessageBox.Show("Telefonnummer muss ausgefüllt werden", "Fehlende Daten", MessageBoxButton.OK, MessageBoxImage.Error);
                    //    return;
                    //}

                    Personen += person + ";";
                    TelNr += textBox.Text + ";";
                }
            }

            if (Personen != null) Personen = Personen.TrimEnd(';');
            if (TelNr != null) TelNr = TelNr.TrimEnd(';');


            if (Personen != null)
            {
                await SQL.CreateAndWriteSQL($"DELETE FROM {MainWindow.table}.firmenPeople WHERE idFirmen = @id", new List<MySqlParameter>()
            {
                new MySqlParameter("@id", _idFirmen)
            });

                await SQL.CreateAndWriteSQL($"INSERT INTO {MainWindow.table}.firmenPeople (idFirmen, Personen, TelNr) VALUES (@id, @personen, @tel)", new List<MySqlParameter>()
            {
                new MySqlParameter("@id", _idFirmen),
                new MySqlParameter("@personen", Personen),
                new MySqlParameter("@tel", TelNr)
            });

                await SQL.CreateAndWriteSQL($"UPDATE {MainWindow.table}.firmen SET Anzahl_Begleiter = @anzahl WHERE idFirmen = @id", new List<MySqlParameter>()
                {
                    new MySqlParameter("@id", _idFirmen),
                    new MySqlParameter("@anzahl", Personen.Split(';').Length)
                });
            }
        }

        private void btnAdd_Click(object sender, RoutedEventArgs e)
        {
            Add();
        }

        private void Add()
        {
            bool zeroPanels = false;
            WrapPanel wrapPanel = new WrapPanel
            {
                Orientation = Orientation.Vertical,  // Jedes WrapPanel wird vertikal sein
                Margin = new Thickness(10),
                Width = 600
            };

            if (Helper.FindVisualChildren<WrapPanel>(spGroupPers).Count() > 0)
            {
                wrapPanel = Helper.FindVisualChildren<WrapPanel>(spGroupPers).Last();
            }
            else
                zeroPanels = true;

            var nr = Helper.FindVisualChildren<TextBlock>(spGroupPers).Where(p => p.Text.StartsWith("Begleitperson")).Count();

            var mainSp = new StackPanel() { Tag = "Count" };
            mainSp.Orientation = Orientation.Horizontal;

            var sp = new StackPanel();
            var lbl = new TextBlock() { Text = $"Begleitperson Nr. {nr + 1}:", Margin = new Thickness(5), Height = 20 };
            lbl.SetResourceReference(Control.ForegroundProperty, SystemColors.ControlTextBrushKey);
            sp.Children.Add(lbl);
            var tb = new TextBox() { Margin = new Thickness(10, 0, 10, 0), Height = 30, Width = 280, ToolTip = "Um eine Person zu entfernen, Feld leer lassen", Tag = "Name" };
            ToolTipService.SetInitialShowDelay(tb, 200);
            MahApps.Metro.Controls.TextBoxHelper.SetWatermark(tb, "Vorname Nachname");
            sp.Children.Add(tb);
            mainSp.Children.Add(sp);

            var tbTel = new TextBox() { Margin = new Thickness(10, 30, 10, 0), Height = 30, Width = 280, HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Top, ToolTip = "Um eine Person zu entfernen, Feld leer lassen", Tag = "Tel" };
            ToolTipService.SetInitialShowDelay(tbTel, 200);
            MahApps.Metro.Controls.TextBoxHelper.SetWatermark(tbTel, "Telefonnummer");
            mainSp.Children.Add(tbTel);


            wrapPanel.Children.Add(mainSp);
            this.Height = this.Height + 60;
            // Das WrapPanel zum StackPanel hinzufügen

            if (zeroPanels)
            {
                spGroupPers.Children.Add(wrapPanel);
                this.Height = this.Height + 20;
                zeroPanels = false;
            }

            //width = (columnCount * 320) + 10;
        }

        private void btnRemove_Click(object sender, RoutedEventArgs e)
        {
            var wrapPanel = Helper.FindVisualChildren<WrapPanel>(spGroupPers).Last();
            wrapPanel.Children.RemoveAt(wrapPanel.Children.Count - 1);
            this.Height = this.Height - 60;
        }


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

        private async void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            await SendIt();
            this.DialogResult = true;
        }

    }
}
