using MahApps.Metro.Controls;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Runtime.CompilerServices;
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 ManageUsers.xaml
    /// </summary>
    public partial class ManageUsers : MetroWindow, INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        public static List<string> RoleList { get; set; } = new List<string>()
        { 
            "Pförtner", 
            "FFK", 
            "Admin", 
            "FFK Sasse", 
            "M2",
            "Organisator",
            "M2 AM"            
        };

        //private List<Users> myVar;
        //public List<Users> UserView
        //{
        //    get { return myVar; }
        //    set { myVar = value; OnPropertyChanged(); }
        //}

        DataTable userList = new DataTable("userList");

        public ManageUsers()
        {
            this.DataContext = this;

            InitializeComponent();
            
            userList = SQL.ReadSQL($"Select * from {MainWindow.table}.users", userList).Result;
            userList.DefaultView.Sort = "Username";
            userList = userList.DefaultView.ToTable();
            //UserView = Users.DataTableToUserList(userList);
            dgUsers.DataContext = userList;
        }

        private async void BtnAddUser_Click(object sender, RoutedEventArgs e)
        {
            if (!await SQL.RowExists("users", "Username", tbUsername.Text))
            {
                if (tbUsername.Text == "")
                {
                    MessageBox.Show("Username eintragen!", "Fehler");
                    return;
                }

                if (cbRole.SelectedIndex == -1)
                {
                    MessageBox.Show("Role auswählen!", "Fehler");
                    return;
                }


                //await SQL.WriteSQL($"Insert into {MainWindow.table}.users (Username,Role) VALUES ('{tbUsername.Text}','{cbRole.SelectedIndex}')");
                await SQL.CreateAndWriteSQL($"Insert into {MainWindow.table}.users (Username,Role) VALUES (@tbUsername,@cbRole_SelectedIndex)", new List<MySqlParameter>()
                                        {
                                            new MySqlParameter("@tbUsername", tbUsername.Text),
                                            new MySqlParameter("@cbRole_SelectedIndex", cbRole.SelectedIndex)
                                        });


                userList = SQL.ReadSQL($"Select * from {MainWindow.table}.users", userList).Result;
                userList.DefaultView.Sort = "Username";
                userList = userList.DefaultView.ToTable();
                //UserView = Users.DataTableToUserList(userList);
                dgUsers.DataContext = userList;

                //dgUsers.ScrollIntoView(UserView.Last());
            }
            else
                MessageBox.Show("Der angegebene User existiert bereits!", "User bereits vorhanden", MessageBoxButton.OK, MessageBoxImage.Error);
        }

        private async void btnDelUser_Click(object sender, RoutedEventArgs e)
        {
            if (dgUsers.SelectedIndex != -1)
            {
                var dg = dgUsers;
                var row = dg.SelectedItem as DataRowView;
                var arr = row.Row.ItemArray;

                await DeleteUser(arr);
            }
        }

        private void BtnClose_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }



        private async void DgUsers_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            var dg = sender as DataGrid;
            var row = dg.SelectedItem as DataRowView;
            var arr = row.Row.ItemArray;

            if (e.Key == Key.Delete)
            {
                await DeleteUser(arr);
            }
        }

        private async Task DeleteUser(object[] arr)
        {
            if (MessageBoxResult.Yes == MessageBox.Show($"User {arr[1]} sicher löschen?", "Sicher löschen?", MessageBoxButton.YesNo, MessageBoxImage.Question))
            {
                await SQL.WriteSQL($"DELETE FROM {MainWindow.table}.users WHERE `Username` = '{arr[1]}'");

                userList = SQL.ReadSQL($"Select * from {MainWindow.table}.users", userList).Result;
                userList.DefaultView.Sort = "Username asc";
                userList = userList.DefaultView.ToTable();
                //UserView = Users.DataTableToUserList(userList);
            }
        }

        private void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            System.Diagnostics.Debug.WriteLine("PropertyChanged   " + propertyName);
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        private async void cbDGRole_DropDownClosed(object sender, EventArgs e)
        {
            var combo = sender as ComboBox;
            //var dg = (combo.DataContext as DataRowView).;
            var row = combo.DataContext as DataRowView;
            var arr = row.Row.ItemArray;

            if (MessageBoxResult.Yes == MessageBox.Show($"Die Rolle des Users {arr[1]} sicher zu {(sender as ComboBox).SelectedValue.ToString()} ändern?", "Sicher ändern?", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.Yes))
            {
                await SQL.WriteSQL($"UPDATE {MainWindow.table}.users SET Role = '{combo.SelectedIndex}' WHERE Username = '{arr[1]}'");

                userList = SQL.ReadSQL($"Select * from {MainWindow.table}.users", userList).Result;
                userList.DefaultView.Sort = "Username";
                userList = userList.DefaultView.ToTable();
                //UserView = Users.DataTableToUserList(userList);
                dgUsers.DataContext = userList;
            }
        }



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

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

        private async void dgUsers_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
        {
            await SQL.CreateAndWriteSQL($"UPDATE {MainWindow.table}.users SET Username = @user WHERE Username = @oldUser", new List<MySqlParameter>
            {
                new MySqlParameter("@user", (e.EditingElement as TextBox).Text),
                new MySqlParameter("@oldUser", ((System.Data.DataRowView)e.Row.Item).Row.ItemArray[1])
            });
        }
    }


    //public class Users
    //{
    //    string Username;
    //    string Role;


    //    public static List<Users> DataTableToUserList(System.Data.DataTable dataTable)
    //    {
    //        List<Users> x = new List<Users>();

    //        foreach (DataRow dr in dataTable.Rows)
    //        {
    //            x.Add(new Users()
    //            {
    //                Username = dr[1].ToString(),
    //                Role = dr[2].ToString()
    //            });
    //        }

    //        return x;
    //    }
    //}
}
