using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Text;
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.Navigation;
using System.Windows.Shapes;
using Sched.CustomClasses;

namespace Sched.CustomSubwindows
{
    /// <summary>
    /// Interaction logic for MultientityPanel.xaml
    /// </summary>
    public partial class MultientityPanel : UserControl
    {
        public class SourceColl : INotifyPropertyChanged
        {
            private ObservableCollection<object> _coll;
            public ObservableCollection<object> Coll
            {
                get { return _coll; }
                set
                {
                    _coll.Clear();
                    foreach (object child in value)
                    {
                        _coll.Add(child);
                    }
                    OnPropertyChanged("Coll");
                }
            }

            public SourceColl()
            {
                _coll = new ObservableCollection<object>();
            }
            public SourceColl(ObservableCollection<object> Coll)
            {
                _coll = Coll;
            }

            public event PropertyChangedEventHandler PropertyChanged;
            private void OnPropertyChanged(string info)
            {
                var handler = PropertyChanged;
                handler?.Invoke(this, new PropertyChangedEventArgs(info));
            }

        }

        public SourceColl SourceTeacher;
        public SourceColl SourceRoom;
        public SourceColl SourceStudentGroup;

        public static RoutedEvent MultientityPanelChangedEvent = EventManager.RegisterRoutedEvent("MultientityPanelChanged", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(MultientityPanel));
        public event RoutedEventHandler MulitentityPanelChanged
        {
            add { AddHandler(MultientityPanelChangedEvent, value); }
            remove { RemoveHandler(MultientityPanelChangedEvent, value); }
        }

        public MultientityPanel()
        {
            InitializeComponent();
            SourceTeacher = new SourceColl(DBI.GetItemsAndOrderByParameter("Teacher", "LastName"));
            SourceRoom = new SourceColl(DBI.GetItemsAndOrderByParameter("Room", "Name"));
            SourceStudentGroup = new SourceColl();

            CB_Room.ItemsSource = SourceRoom.Coll;
            CB_Teacher.ItemsSource = SourceTeacher.Coll;
            CB_StudentGroup.ItemsSource = SourceStudentGroup.Coll;

            CB_Room.SelectionChanged += MultiEntityCB_SelectionChanged;
            CB_Teacher.SelectionChanged += MultiEntityCB_SelectionChanged;
            CB_StudentGroup.SelectionChanged += MultiEntityCB_SelectionChanged;

            BTN_Room.Click += BTN_Click_AddEntity;
            BTN_Teacher.Click += BTN_Click_AddEntity;
            BTN_StudentGroup.Click += BTN_Click_AddEntity;
        }

        //Lesson
        public void FillSubgrids()
        {
            //Find the specified subgrid and fill in comboboxes
            List<string> subgridList = new List<string> { "Teacher", "Room", "StudentGroup" };
            var DA = DataContext as AssignmentData;
            if (DA != null)
            {
                List<int> listIds = new List<int>();

                foreach (string gridN in subgridList)
                {
                    listIds.Clear();
                    foreach (int id in DA.Lssn.GetEntities(gridN))
                    {
                        listIds.Add(id);
                    }

                    Grid chosenGrid = G_StudentGroup;
                    Button associatedButton = BTN_StudentGroup;
                    ComboBox associateComboBox = CB_StudentGroup;

                    if (gridN == "Teacher")
                    {
                        chosenGrid = G_Teacher;
                        associatedButton = BTN_Teacher;
                        associateComboBox = CB_Teacher;
                    }
                    else if (gridN == "Room")
                    {
                        chosenGrid = G_Room;
                        associatedButton = BTN_Room;
                        associateComboBox = CB_Room;
                    }

                    FillGrid(chosenGrid, associatedButton, associateComboBox, listIds);
                }
            }
        }
        private void FillGrid(Grid g, Button btn, ComboBox CB, List<int> listIds)
        {
            //Remove all children but first row
            for (int i = (g.Children.Count - 1); 0 <= i; i--)
            {
                UIElement child = g.Children[i];
                int row = Grid.GetRow(child);
                if (row != 0)
                {
                    g.Children.Remove(child);
                }
            }

            //Add however many rows are needed
            for (int i = 1; i < listIds.Count; i++)
            {
                BTN_Click_AddEntity(btn, new RoutedEventArgs());
            }

            //Get currently selected item
            int selectedId = -1;
            if (CB.SelectedItem != null)
            {
                selectedId = (int)CB.SelectedItem.GetType().GetProperty("Id").GetValue(CB.SelectedItem);
                if (!(listIds.Contains(selectedId)))
                {
                    CB.SelectedItem = null;
                }
            }
            for (int i = 0; i < listIds.Count; i++)
            {
                int id = listIds[i];
                if (id == selectedId)
                {
                    continue;   //selectedId already assigned to row 0
                }

                foreach (UIElement child in g.Children)
                {
                    var cBox = child as ComboBox;
                    if (cBox != null)
                    {
                        if (cBox.SelectedIndex == -1) //no selection - can add something
                        {
                            foreach (var item in cBox.ItemsSource)
                            {

                                if ((int)item.GetType().GetProperty("Id").GetValue(item) == id)
                                {
                                    cBox.SelectedItem = item;
                                    break;
                                }
                            }
                            break;
                        }
                    }
                }
            }

            UpdateMultiEntityData(g.Name);
        }


        //Lesson - MultiEntity Grids (Rooms,Teachers,StudentGroups) 
        private void BTN_Click_AddEntity(object sender, RoutedEventArgs e)
        {
            var btn = sender as Button;
            if (btn != null)
            {
                ComboBox cb = new ComboBox();
                Grid chosenGrid = (Grid)btn.Parent;
                string chosenGridName = chosenGrid.Name;

                if (chosenGridName == "G_Room")
                {
                    cb.ItemsSource = CB_Room.ItemsSource;
                }
                else if (chosenGridName == "G_Teacher")
                {
                    cb.ItemsSource = CB_Teacher.ItemsSource;
                }
                else
                {
                    cb.ItemsSource = CB_StudentGroup.ItemsSource;
                }

                chosenGrid.RowDefinitions.Add(new RowDefinition()); //must add new row to main grid to accomodate these new controls
                int row = chosenGrid.RowDefinitions.Count - 1;

                Grid.SetRow(cb, row);
                Grid.SetColumn(cb, 0);
                chosenGrid.Children.Add(cb);

                Button btn2 = new Button();
                btn2.Background = Brushes.Red;
                btn2.Content = "-";
                Grid.SetRow(btn2, row);
                Grid.SetColumn(btn2, 1);
                chosenGrid.Children.Add(btn2);

                btn2.Click += BTN_Click_RemoveEntity;
                cb.SelectionChanged += MultiEntityCB_SelectionChanged;
            }
        }
        private void BTN_Click_RemoveEntity(object sender, RoutedEventArgs e)
        {
            var btn = sender as Button;
            if (btn != null)
            {
                Grid chosenGrid = (Grid)btn.Parent;

                int delRow = Grid.GetRow(btn);
                for (int i = (chosenGrid.Children.Count - 1); 0 <= i; i--)   //start from end to ensure all children are checked
                {
                    var child = chosenGrid.Children[i];
                    int row = Grid.GetRow(child);
                    if (row == delRow)
                    {
                        chosenGrid.Children.RemoveAt(i);    //remove the ComboBox and Button in that row
                    }
                }
                for (int i = (chosenGrid.Children.Count - 1); 0 <= i; i--)
                {
                    var child = chosenGrid.Children[i];
                    int row = Grid.GetRow(child);  //All other children to be shifted one row index down if they are on higher indexes
                    if (row > delRow)
                    {
                        Grid.SetRow(child, (row - 1));
                    }
                }
                int lastRow = chosenGrid.RowDefinitions.Count - 1;
                chosenGrid.RowDefinitions.RemoveAt(lastRow);

                string G_name = chosenGrid.Name;
                UpdateMultiEntityData(G_name);
            }
        }
        private void MultiEntityCB_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var cb = sender as ComboBox;
            if (cb != null)
            {
                var chosenGrid = cb.Parent as Grid;
                if (chosenGrid != null)
                {
                    string G_name = chosenGrid.Name;
                    UpdateMultiEntityData(G_name);
                }
            }
        }
        private void UpdateMultiEntityData(string gridName)  //MultiEntity - Teachers, Rooms, Groups....
        {
            var AD = this.DataContext as AssignmentData;
            if (AD != null)
            {
                Grid chosenGrid = G_StudentGroup;
                if (gridName == "G_Room")
                {
                    chosenGrid = G_Room;
                }
                else if (gridName == "G_Teacher")
                {
                    chosenGrid = G_Teacher;
                }
                string categoryName = chosenGrid.Name.Substring(2);

                List<int> idsList = new List<int>();
                foreach (var child in chosenGrid.Children)
                {
                    if (child.GetType() == typeof(ComboBox))
                    {
                        var cb2 = child as ComboBox;
                        if (cb2.SelectedItem != null)
                        {
                            object selItem = cb2.SelectedItem;
                            int Id = (int)selItem.GetType().GetProperty("Id").GetValue(selItem);
                            idsList.Add(Id);
                        }
                    }
                }
                AD.Lssn.SetEntities(categoryName, idsList);
                RaiseEvent(new RoutedEventArgs(MultientityPanelChangedEvent, this));
            }
        }

    }
}
