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

namespace InABox.Mobile
{
    
    public class MobileMenuButtonLayoutChangedEventArgs : EventArgs
    {
        public int RowCount { get; private set; }

        public MobileMenuButtonLayoutChangedEventArgs(int rowcount)
        {
            RowCount = rowcount;
        }
    }
    public delegate void MobileMenuButtonLayoutChangedEvent(object sender, MobileMenuButtonLayoutChangedEventArgs args);
    
    public class MobileMenuButtonMenuViewModel : BindableObject
    {
        private readonly ObservableCollection<MobileMenuEntry> _items;
        public IList<MobileMenuEntry> Items => _items;

        private readonly ObservableCollection<MobileMenuEntry> _visibleItems;
        public IList<MobileMenuEntry> VisibleItems => _visibleItems;
        
        public event MobileMenuButtonLayoutChangedEvent LayoutChanged;

        public event EventHandler ItemClicked;

        public bool ShowImages { get; set; }
        public MobileMenuButtonMenuImagePosition ImagePosition { get; set; }

        public MobileMenuButtonMenuViewModel()
        {
            _items = new ObservableCollection<MobileMenuEntry>();

            _visibleItems = new ObservableCollection<MobileMenuEntry>();
            _items.CollectionChanged += (sender, args) =>
            {
                
                DoLayout();
            };
        }

        private void DoLayout()
        {
            VisibleItems.Clear();
            int iRow = 0;
            foreach (var item in Items.Where(x => x.IsVisible))
            {
                item.Index = iRow;
                item.VisibleChanged = DoLayout;
                item.AfterClick = () => ItemClicked?.Invoke(this, EventArgs.Empty);
                VisibleItems.Add(item);
                iRow++;
            }
            LayoutChanged?.Invoke(this,new MobileMenuButtonLayoutChangedEventArgs(iRow));
        }
    }
}