using MahApps.Metro.Controls;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Linq;
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 KartenTausch.xaml
    /// </summary>
    public partial class KartenTausch : MetroWindow
	{

        public KartenTausch()
        {
            InitializeComponent();

            cbRot.ItemsSource = SQL.ReadListString($"SELECT kartennr From {MainWindow.table}.karten WHERE farbe = 'Rot'").Result;

            Helper.InitSerial();
            Helper.DataReceived += Helper_DataReceived;
        }

        private void cbRot_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var info = SQL.ReadListStringTwoColumns($"SELECT benutzer,telnr From {MainWindow.table}.karten WHERE kartennr = '{(sender as ComboBox).SelectedValue}'").Result;
            var split = info.First().ToString().Split(';');

            if (split.Length > 1)
                lblRotInfo.Text = $"Benutzer:  {split[0]}    Telefon:  {split[1]}";
        }


        private void Helper_DataReceived(object sender, string e)
        {
            Dispatcher.Invoke(() =>
            {
                if (cbRot.ItemsSource.Cast<string>().ToList().Contains(e.Split('=')[0].ToString()))
                    cbRot.SelectedValue = e.Split('=')[0].ToString();
                else if (cbRot.SelectedIndex != -1 || tbGruen.IsKeyboardFocused)
                    tbGruen.Text = e.Split('=')[0].ToString();

            });
        }



        private async void btnClose_Click(object sender, RoutedEventArgs e)
        {
            byte[] _signature = null;


            var info = SQL.ReadListStringTwoColumns($"SELECT benutzer,telnr From {MainWindow.table}.karten WHERE kartennr = '{cbRot.SelectedValue}'").Result;
            var split = info.First().ToString().Split(';');

            var sig = new Signature(Signature.DisclaimerType.Gruen, split[0], split[1]);

            if (cbRot.SelectedIndex != -1 && !string.IsNullOrWhiteSpace(tbGruen.Text))
            {
                if (sig.ShowDialog() == false)
                {
                    _signature = sig.ResultByte;

                    if (_signature != null)
                    {
                        var red = SQL.ReadListStringMultipleColumns($"SELECT * From {MainWindow.table}.karten WHERE kartennr = '{cbRot.SelectedValue}'", 5).Result.First().Split(';');
                        SQL.WriteSQL($"DELETE FROM {MainWindow.table}.karten WHERE kartennr = '{red[1]}'");

                        //SQL.WriteSQL($"INSERT INTO {MainWindow.table}.karten (kartennr,farbe,benutzer,telnr,AusgegebenDurch,AusgegebenTimestamp,Signature) VALUES ('{tbGruen.Text}','Grün','{red[3]}','{red[4]}','{Environment.UserName}','{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}', @signature)", _signature);
                        var cmd = SQL.CreateAndReturnSQLCommand($"INSERT INTO {MainWindow.table}.karten (kartennr,farbe,benutzer,telnr,AusgegebenDurch,AusgegebenTimestamp,Signature) VALUES (@tbGruen,'Grün',@red3,@red4,@UserName,@Date, @signature)", new List<MySqlParameter>()
                                            {
                                                new MySqlParameter("@tbGruen", tbGruen.Text),
                                                new MySqlParameter("@red3", red[3]),
                                                new MySqlParameter("@red4", red[4]),
                                                new MySqlParameter("@UserName", Environment.UserName),
                                                new MySqlParameter("@Date", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"))
                                            });

                        await SQL.CreateAndWriteSQLwithSignature(cmd, _signature);

                        this.Close();
                    }
                }
            }
        }



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

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