using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Xamarin.Forms;

namespace Aurora.Design.Components.NavigationMenu
{
    public partial class NavigationMenu : ContentView
    {
        public NavigationMenu()
        {
            InitializeComponent();
            ListView = MenuItemsListView;
        }

        public ListView ListView;

        public static readonly BindableProperty ItemsProperty =
            BindableProperty.Create(propertyName: nameof(Items),
                returnType: typeof(ObservableCollection<NavigationItem>),
                declaringType: typeof(NavigationMenu),
                defaultBindingMode: BindingMode.TwoWay,
                propertyChanged: OnItemsChanged);

        public ObservableCollection<NavigationItem> Items
        {
            get
            {
                return (ObservableCollection<NavigationItem>)GetValue(ItemsProperty);
            }
            set
            {
                SetValue(ItemsProperty, value);
            }
        }

        /// <summary>
        /// Items changed event handler. Organizes items in groups for display.
        /// </summary>
        /// <param name="bindable">The changed Item.</param>
        /// <param name="oldValue">The previous value.</param>
        /// <param name="newValue">The new value.</param>
        private static void OnItemsChanged(BindableObject bindable, object oldValue, object newValue)
        {
            var control = (NavigationMenu)bindable;
            ObservableCollection<NavigationItem> items = (ObservableCollection<NavigationItem>)newValue;
            Dictionary<string, NavigationGroupItem> groupDictioanry = new Dictionary<string, NavigationGroupItem>();

            //Populate dictionary where group heading is the key
            foreach (NavigationItem item in items)
            {
                if (groupDictioanry.ContainsKey(item.Group))
                {
                    groupDictioanry.TryGetValue(item.Group, out var groupItem);
                    groupItem.Items.Add(item);
                }
                else
                {
                    NavigationGroupItem groupItem = new NavigationGroupItem(item.Group);
                    groupItem.Add(item);

                    groupDictioanry.Add(item.Group, groupItem);
                }
            }

            ObservableCollection<NavigationGroupItem> groups = new ObservableCollection<NavigationGroupItem>();
            foreach (string groupHeading in groupDictioanry.Keys)
            {
                groupDictioanry.TryGetValue(groupHeading, out var groupItem);
                groups.Add(groupItem);
            }

            control.MenuItemsListView.ItemsSource = groups;
        }

    }
}