using DataAccessLibrary.DataAccess;
using DataAccessLibrary.Models;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=234238

namespace GolfComp.Views
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class SpelerListpage : Page, INotifyPropertyChanged
    {
        ObservableCollection<SpelerModel> speler = new ObservableCollection<SpelerModel>();
        ObservableCollection<GolfclubModel> golfclub = new ObservableCollection<GolfclubModel>();      
        
        bool enableCommandBar = true;
        public SpelerListpage()
        {
            this.InitializeComponent();
            newRecordStackPanel.Visibility = Visibility.Collapsed;
        }
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            GetData();
            WireUpSpelerDropDown();

            if (Datagrid.ItemsSource == null)
            {
                Datagrid.ItemsSource = speler;
            }

            

        }        

        private void WireUpSpelerDropDown()
        {
            string sql = "select * from Golfclub ";
            var golfclublijst = SqliteDataAccess.LoadData<GolfclubModel>(sql, new Dictionary<string, object>());

            golfclublijst.ForEach(x => golfclub.Add(x));

            golfclubDropDown.ItemsSource = golfclub;
            golfclubDropDown.DisplayMemberPath = "Naam";
            golfclubDropDown.SelectedValuePath = "Id";
        }
        public void GetData()
        {           
            string sql = "SELECT Speler.Id, Voornaam, Achternaam, Handicap, ClubId, Naam, Telefoon, Email from Speler INNER JOIN Golfclub ON Golfclub.Id = Speler.ClubId ORDER BY Achternaam; ";

            var spelerlijst = SqliteDataAccess.LoadData<SpelerModel>(sql, new Dictionary<string, object>());

            spelerlijst.ForEach(x => speler.Add(x));
        }    
        private void Delete_Click(object sender, RoutedEventArgs e)
        {
           
            string sql = "delete from Speler where Id = @Id";

            try
            {
                Dictionary<string, object> parameters = new Dictionary<string, object>
                {
                    { "@Id", SelectedItem.Id }
                };
                SqliteDataAccess.DeleteData(sql, parameters);
                speler.Clear();
                GetData();
            }
            catch
            {
                MessageDialog messagedialog = new MessageDialog("Fout: Selecteer een record");
                _ = messagedialog.ShowAsync();

                return;
            }
        }
        private void UpdateRecord_Click(object sender, RoutedEventArgs e)
        {
            string sql = "update Speler set Voornaam = @Voornaam, Achternaam = @Achternaam, Handicap = @Handicap " +
                "Telefoon = @Telefoon, Email = @Email, ClubId = @ClubId, TeamId = @TeamId " +
                "PuntenVoor = @PuntenVoor, PuntenTegen = @PuntenTegen " +
                "where Id = @Id";

            try
            {
                Dictionary<string, object> parameters = new Dictionary<string, object>
                {
                    { "@Id", SelectedItem.Id},
                    { "@Voornaam", SelectedItem.Voornaam },
                    { "@Achternaam", SelectedItem.Achternaam},
                    { "@Handicap", SelectedItem.Handicap},
                    { "@Telefoon", SelectedItem.Telefoon},
                    { "@Email", SelectedItem.Email},
                    { "@ClubId", SelectedItem.ClubId},
                    { "@TeamId", SelectedItem.TeamId},
                    { "@PuntenVoor", SelectedItem.PuntenVoor},
                    { "@PuntenTegen", SelectedItem.PuntenTegen}
                };
                SqliteDataAccess.SaveData(sql, parameters);
                speler.Clear();
                GetData();

                MessageDialog messagedialog = new MessageDialog("Succes: wijzigingen weggeschreven");
                _ = messagedialog.ShowAsync();
            }
            catch
            {
                MessageDialog messagedialog = new MessageDialog("Fout: Selecteer een record");
                _ = messagedialog.ShowAsync();

                return;
            }
        }
        private void Insert_new_entry(object sender, RoutedEventArgs e)
        {
            enableCommandBar = false;
            newRecordStackPanel.Visibility = Visibility.Visible;
        }
        private void DeleteNewRecord_Click(object sender, RoutedEventArgs e)
        {
            VoorNaamTextBox.Text = "";
            AchternaamTextBox.Text = "";
            HandicapTextBox.Text = "";

            enableCommandBar = true;
            newRecordStackPanel.Visibility = Visibility.Collapsed;
        }
        private (bool isValid, SpelerModel model) ValidateForm()
        {
            bool isValid = true;
            SpelerModel model = new SpelerModel();

            try
            {
                model.Voornaam = VoorNaamTextBox.Text;
                model.Achternaam = AchternaamTextBox.Text;
                model.Handicap = double.Parse(HandicapTextBox.Text);
                model.Telefoon = TelefoonTextBox.Text;
                model.Email = EmailTextBox.Text;
                model.ClubId = (int)golfclubDropDown.SelectedValue;
                model.TeamId = 1;
                model.PuntenVoor = 0;
                model.PuntenTegen = 0;

            }
            catch
            {
                isValid = false;
            }
            return (isValid, model);
        }
        private void SaveNewRecord_Click(object sender, RoutedEventArgs e)
        {
            SpelerModel model = new SpelerModel();

            string sql = "insert into Speler (Voornaam, Achternaam, Handicap, Telefoon, Email, ClubId, TeamId, PuntenVoor, PuntenTegen) " +
                "values (@Voornaam, @Achternaam, @Handicap, @Telefoon, @Email, @ClubId, @TeamId, @PuntenVoor, @PuntenTegen)";

            var form = ValidateForm();
            if (form.isValid == false)
            {
                MessageDialog messagedialog = new MessageDialog("foutieve invoer. Probeer het opnieuw");

                _ = messagedialog.ShowAsync();

                return;
            }
            if (VoorNaamTextBox.Text == "" || AchternaamTextBox.Text == "")
            {
                MessageDialog messagedialog = new MessageDialog("Vul alle velden in");

                _ = messagedialog.ShowAsync();

                return;
            }
            Dictionary<string, object> parameters = new Dictionary<string, object>
            {
                {"@Voornaam", form.model.Voornaam },
                {"@Achternaam", form.model.Achternaam },
                {"@Handicap", form.model.Handicap },
                {"@Telefoon", form.model.Telefoon },
                {"@Email", form.model.Email },
                {"@ClubId", form.model.ClubId },
                {"@TeamId", form.model.TeamId },
                {"@PuntenVoor", form.model.PuntenVoor },
                {"@PuntenTegen", form.model.PuntenTegen }

            };
            SqliteDataAccess.SaveData(sql, parameters);
            //speler.Add(form.model);

            VoorNaamTextBox.Text = "";
            AchternaamTextBox.Text = "";
            HandicapTextBox.Text = "";
            

            enableCommandBar = true;
            newRecordStackPanel.Visibility = Visibility.Collapsed;

            speler.Clear();
            GetData();
            WireUpSpelerDropDown();

        }
        public event PropertyChangedEventHandler PropertyChanged;
        public void OnPropertyChanged([CallerMemberName] string propertyName = null) =>
             PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));

        private SpelerModel _selectedItem;

        public SpelerModel SelectedItem
        {
            get => _selectedItem;
            set
            {
                if (_selectedItem != value)
                {
                    _selectedItem = value;
                    OnPropertyChanged();
                }
            }
        }
    }
}
