using Microsoft.Toolkit.Uwp.Notifications;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.UI.WebControls;
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 NotificationSettings.xaml
    /// </summary>
    public partial class NotificationSettings : Window
    {
        DataTable table = new DataTable("Firmen");
        List<string> visitorList = new List<string>(); 



        public NotificationSettings()
        {
            InitializeComponent();
        }

        private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            table.Clear();
            cBVisitor.ItemsSource = null;
            cbWin.IsEnabled = false;
            cbMail.IsEnabled = false;
            cbSMS.IsEnabled = false;

            switch (((sender as ComboBox).SelectedItem as ComboBoxItem).Content)
            {
                case "Firma":
                    tbChoose.Text = "Firma wählen:";
                    cBVisitor.IsEnabled = true;
                    if (MainWindow.LoggedInRole == Roles.Admin || MainWindow.LoggedInRole == Roles.Pförtner || MainWindow.LoggedInRole == Roles.Controller)
                    {
                        requestFirmen(true);
                    }
                    else
                    {
                        requestFirmen(false);
                    }
                    break;
                case "Besucher":
                    tbChoose.Text = "Besucher wählen:";
                    cBVisitor.IsEnabled = true;
                    if (MainWindow.LoggedInRole == Roles.Admin || MainWindow.LoggedInRole == Roles.Pförtner || MainWindow.LoggedInRole == Roles.Controller)
                    {
                        requestBesucher(true);
                    }
                    else
                    {
                        requestFirmen(false);
                    }
                    break;
                case "Lieferant":
                    tbChoose.Text = "Lieferant wählen:";
                    cBVisitor.IsEnabled = true;
                    if (MainWindow.LoggedInRole == Roles.Admin || MainWindow.LoggedInRole == Roles.Pförtner || MainWindow.LoggedInRole == Roles.Controller)
                    {
                        requestLieferant(true);
                    }
                    else
                    {
                        requestLieferant(false);
                    }
                    break;
                case "DB Notdienst":
                    tbChoose.Text = "DB Notdienst wählen:";
                    cBVisitor.IsEnabled = true;
                    if (MainWindow.LoggedInRole == Roles.Admin || MainWindow.LoggedInRole == Roles.Pförtner || MainWindow.LoggedInRole == Roles.Controller)
                    {
                        requestDB(true);
                    }
                    else
                    {
                        requestDB(false);
                    }
                    break;
                case "":
                    cBVisitor.IsEnabled = false;
                    break;
            }
        }




        private void requestBesucher(bool isAdmin = false)
        {
            if (!isAdmin)
            {
                table = SQL.ReadSQL($"SELECT Name,Ersteller FROM zkup.besucher WHERE Ersteller = '{Environment.UserName}' " +
                        $"OR Ersteller = '{Environment.UserDomainName}{Environment.UserName}' " +
                        $"OR Ersteller = '{SQL.ReadSingleValue($"SELECT Vertreter FROM zkup.ansprechpartner WHERE Name = '{Helper.InsertSpaceBeforeUpperCase(Environment.UserName)}'")}' " +
                        $"OR Ansprechpartner_Intern = '{Helper.InsertSpaceBeforeUpperCase(Environment.UserName)}' GROUP BY Name"
                        , table).Result;

                var list = table.Select().Select(p => p.ItemArray[0]).ToList();
                list.Sort();
                cBVisitor.ItemsSource = list.Cast<string>();
            }
            else
            {
                table = SQL.ReadSQL("SELECT Name FROM zkup.besucher GROUP BY Name", table).Result;
                //FirmaView = Firma.DataTableToFirma(firmen);
                //dgFirmen.DataContext = firmen;

                var list = table.Select().Select(p => p.ItemArray[0]).ToList();
                list.Sort();
                cBVisitor.ItemsSource = list.Cast<string>();
            }
        }

        private void requestFirmen(bool isAdmin = false)
        {
            if (!isAdmin)
            {
                table = SQL.ReadSQL($"SELECT Name,Ersteller FROM zkup.firmen WHERE Ersteller = '{Environment.UserName}' " +
                    $"OR Ersteller = '{Environment.UserDomainName}{Environment.UserName}' " +
                    $"OR Ersteller = '{SQL.ReadSingleValue($"SELECT Vertreter FROM zkup.ansprechpartner WHERE Name = '{Helper.InsertSpaceBeforeUpperCase(Environment.UserName)}'").Replace("-", "").Replace(" ", "")}' " +
                    $"OR Ersteller = '{Environment.UserDomainName}{SQL.ReadSingleValue($"SELECT Vertreter FROM zkup.ansprechpartner WHERE Name = '{Helper.InsertSpaceBeforeUpperCase(Environment.UserName)}'").Replace("-", "").Replace(" ", "")}' " +
                    $"OR Ersteller = '{SQL.ReadSingleValue($"SELECT Name FROM zkup.ansprechpartner WHERE Vertreter = '{Helper.InsertSpaceBeforeUpperCase(Environment.UserName)}'").Replace("-", "").Replace(" ", "")}' " +
                    $"OR Ersteller = '{Environment.UserDomainName}{SQL.ReadSingleValue($"SELECT Name FROM zkup.ansprechpartner WHERE Vertreter = '{Helper.InsertSpaceBeforeUpperCase(Environment.UserName)}'").Replace("-", "").Replace(" ", "")}' " +
                    $"OR Ansprechpartner_Intern = '{Helper.InsertSpaceBeforeUpperCase(Environment.UserName)}' GROUP BY Name"
                    , table).Result;
                //FirmaView = Firma.DataTableToFirma(firmen);
                //dgFirmen.DataContext = firmen;
                var list = table.Select().Select(p => p.ItemArray[0]).ToList();
                list.Sort();
                cBVisitor.ItemsSource = list.Cast<string>();
            }
            else
            {
                table = SQL.ReadSQL("SELECT Name FROM zkup.firmen GROUP BY Name", table).Result;
                //FirmaView = Firma.DataTableToFirma(firmen);
                //dgFirmen.DataContext = firmen;

                var list = table.Select().Select(p => p.ItemArray[0]).ToList();
                list.Sort();
                cBVisitor.ItemsSource = list.Cast<string>();
            }
        }

        private void requestLieferant(bool isAdmin = false)
        {
            table = SQL.ReadSQL("Select MAX(Firma), MAX(Fahrer) from zkup.lieferanten WHERE Firma NOT LIKE 'DB%' GROUP BY Firma", table).Result;
            var list = table.Select().Select(p => "Firma: " + p.ItemArray[0].ToString() + ", Fahrer: " + p.ItemArray[1]).ToList();
            list.Sort();
            cBVisitor.ItemsSource = list.Cast<string>();
        }

        private void requestDB(bool isAdmin = false)
        {
            table = SQL.ReadSQL("SELECT MAX(Firma), MAX(Fahrer) FROM zkup.lieferanten WHERE Firma LIKE 'DB%' GROUP BY Firma", table).Result;
            var list = table.Select().Select(p => "Firma: " + p.ItemArray[0].ToString() + ", Fahrer: " + p.ItemArray[1]).ToList();
            list.Sort();
            cBVisitor.ItemsSource = list.Cast<string>();
        }









        private void cBVisitor_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            cbWin.IsEnabled = true;            
            cbMail.IsEnabled = true;
            tbMail.IsEnabled = true;
            cbSMS.IsEnabled = true;
            tbSMS.IsEnabled = true;
        }

        private void cbSMS_Checked(object sender, RoutedEventArgs e)
        {
            tbSMS.IsEnabled = true;
        }

        private void cbSMS_Unchecked(object sender, RoutedEventArgs e)
        {
            tbSMS.IsEnabled = false;
        }

        private void cbMail_Checked(object sender, RoutedEventArgs e)
        {
            tbMail.IsEnabled = true;
        }

        private void cbMail_Unchecked(object sender, RoutedEventArgs e)
        {
            tbMail.IsEnabled = false;
        }




        private void btnAddNotification_Click(object sender, RoutedEventArgs e)
        {
            var NotiWin = cbWin.IsChecked.Value ? "1" : "0";
            var NotiMail = cbMail.IsChecked.Value ? "1" : "0";
            var NotiSms = cbSMS.IsChecked.Value ? "1" : "0";
            var type = $"{NotiWin};{NotiMail};{NotiSms}";

            SQL.WriteSQL($"REPLACE INTO zkup.notification (Username, Visitor, Category, NotificationType) VALUES ('{Environment.UserName}', '{cBVisitor.Text}', {cbCategory.SelectedIndex}, '{type}', '{tbMail.Text}', '{tbSMS.Text}')");
        }





        //private async void ShowToastSelected(DataTable dt)
        //{
        //    try
        //    {
        //        bool isAdminEntry = false;
        //        if (LoggedInRole == Roles.Admin)
        //        {
        //            var vertAspName = SQL.ReadSingleValue($"SELECT Vertreter FROM zkup.ansprechpartner WHERE Name = '{Helper.InsertSpaceBeforeUpperCase(Environment.UserName)}'").Replace("-", "").Replace(" ", "");
        //            var nameAspVert = SQL.ReadSingleValue($"SELECT Name FROM zkup.ansprechpartner WHERE Vertreter = '{Helper.InsertSpaceBeforeUpperCase(Environment.UserName)}'").Replace("-", "").Replace(" ", "");

        //            var check = await SQL.ReadSQL($"SELECT * FROM zkup.zutritte where Zutritt >= now() + INTERVAL -20 SECOND AND (idFirma_Besucher IN (select idfirmen from zkup.firmen where Ersteller = '{Environment.UserName}' " +
        //                 $"OR Ersteller = '{Environment.UserDomainName}{Environment.UserName}' " +
        //                 $"OR Ersteller = '{vertAspName}' " +
        //                 $"OR Ersteller = '{Environment.UserDomainName}{vertAspName}' " +
        //                 $"OR Ersteller = '{nameAspVert}' " +
        //                 $"OR Ersteller = '{Environment.UserDomainName}{nameAspVert}' " +
        //                 $"OR Ansprechpartner_Intern = '{Helper.InsertSpaceBeforeUpperCase(Environment.UserName)}') " +
        //                 $"OR idFirma_Besucher IN (select idbesucher from zkup.besucher where Ersteller = '{Environment.UserName}' " +
        //                 $"OR Ersteller = '{Environment.UserDomainName}{Environment.UserName}' " +
        //                 $"OR Ersteller = '{vertAspName}' " +
        //                 $"OR Ersteller = '{Environment.UserDomainName}{vertAspName}' " +
        //                 $"OR Ersteller = '{nameAspVert}' " +
        //                 $"OR Ersteller = '{Environment.UserDomainName}{nameAspVert}' " +
        //                 $"OR Ansprechpartner_Intern = '{Helper.InsertSpaceBeforeUpperCase(Environment.UserName)}'))");

        //            isAdminEntry = check.Rows.Count > 0;
        //        }

        //        if (LoggedInRole != Roles.Pförtner)
        //        {
        //            //1 = Firma
        //            if (int.Parse(dt.Rows[0].ItemArray[1].ToString()) == 1)
        //            {
        //                if (dt.Rows[0].ItemArray[14] != DBNull.Value)
        //                {
        //                    if ((LoggedInRole == Roles.Admin && isAdminEntry) || (LoggedInRole != Roles.Admin))
        //                    {
        //                        var idFirmaBesucher = dt.Rows[0].ItemArray[14];

        //                        var firma = dt.Rows[0].ItemArray[2];
        //                        var name = dt.Rows[0].ItemArray[8].ToString().Split('/')[0];
        //                        var anzPers = dt.Rows[0].ItemArray[6].ToString();

        //                        var begleit = int.Parse(anzPers) == 1 ? "Begleitperson" : "Begleitpersonen";

        //                        new ToastContentBuilder()
        //                            .AddAppLogoOverride(new Uri(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\ZKuP.png"), ToastGenericAppLogoCrop.Circle)
        //                            .AddText($"Firma {firma}")
        //                            .AddText($"{name} ist mit")
        //                            .AddText($"{anzPers} {begleit} angekommen")
        //                            .SetToastDuration(ToastDuration.Long)
        //                            .Show(t => t.ExpirationTime = DateTime.Now.AddHours(2));
        //                    }
        //                }
        //            }// 2 = Besucher
        //            else if (int.Parse(dt.Rows[0].ItemArray[1].ToString()) == 2)
        //            {
        //                if (dt.Rows[0].ItemArray[14] != DBNull.Value)
        //                {
        //                    if ((LoggedInRole == Roles.Admin && isAdminEntry) || (LoggedInRole != Roles.Admin))
        //                    {
        //                        var firma = dt.Rows[0].ItemArray[2];
        //                        var name = dt.Rows[0].ItemArray[8].ToString().Split('/')[0];
        //                        var anzPers = dt.Rows[0].ItemArray[6].ToString();

        //                        var begleit = int.Parse(anzPers) == 1 ? "Begleitperson" : "Begleitpersonen";

        //                        new ToastContentBuilder()
        //                            .AddAppLogoOverride(new Uri(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\ZKuP.png"), ToastGenericAppLogoCrop.Circle)
        //                            .AddText($"Besucher {name}")
        //                            .AddText($"mit {anzPers} {begleit}")
        //                            .AddText($"angekommen")
        //                            .SetToastDuration(ToastDuration.Long)
        //                            .Show(t => t.ExpirationTime = DateTime.Now.AddHours(2));
        //                    }
        //                }
        //            }
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        Log.WriteLog(ex.Message);
        //    }
        //}

    }
}
