using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace InABox.Mobile
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class MobilePageStack
    {
        public IList<MobilePageStackItem> Items { get; private set; }
        
        private MobilePageStackItem _current;
        public MobilePageStackItem SelectedItem 
        {
            get => _current;
            set
            {
                if (_current != null)
                    _current.DoDisappearing();
                _current = value;
                Content = _current?.Content;
                _current?.DoAppearing();
                SelectionChanged?.Invoke(this, EventArgs.Empty);
            }
        }
        
        public event EventHandler SelectionChanged;

        public MobilePageStack()
        {
            var items = new ObservableCollection<MobilePageStackItem>();
            items.CollectionChanged += ItemsChanged;
            Items = items;
            InitializeComponent();
        }

        private void ItemsChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            Device.BeginInvokeOnMainThread(() =>
            {
                SelectedItem ??= Items.FirstOrDefault();
            });
        }
    }
}