using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.CommunityToolkit.Converters;
using Xamarin.CommunityToolkit.UI.Views;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace InABox.Mobile
{

    public class MobileMenuButtonMenuImagePositionConverter : BaseConverter<MobileMenuButtonMenuImagePosition, Dock>
    {
        public override Dock ConvertFrom(MobileMenuButtonMenuImagePosition value)
        {
            return value == MobileMenuButtonMenuImagePosition.Left
                ? Dock.Left
                : Dock.Right;
        }

        public override MobileMenuButtonMenuImagePosition ConvertBackTo(Dock value)
        {
            return value == Dock.Right
                ? MobileMenuButtonMenuImagePosition.Right
                : MobileMenuButtonMenuImagePosition.Left;
        }
    }
    
    public enum MobileMenuButtonMenuImagePosition
    {
        Left,
        Right
    }
    
    public class MobileMenuButtonTemplateSelector : DataTemplateSelector
    {
        public DataTemplate Item { get; set; }
        public DataTemplate Separator { get; set; }

        protected override DataTemplate OnSelectTemplate (object item, BindableObject container)
        {
            return item is MobileMenuItem
                ? Item
                : Separator;
        }
    }
    
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class MobileMenuButtonMenu
    {
        public IList<MobileMenuEntry> Items => _viewModel.Items;
        
        public IList<MobileMenuEntry> VisibleItems => _viewModel.VisibleItems;

        public bool ShowImages
        {
            get => _viewModel.ShowImages;
            set => _viewModel.ShowImages = value;
        }

        public MobileMenuButtonMenuImagePosition ImagePosition
        {
            get => _viewModel.ImagePosition;
            set => _viewModel.ImagePosition = value;
        }
        
        public MobileMenuButtonMenu()
        {
            InitializeComponent();
        }

        private void TapGestureRecognizer_OnTapped(object sender, EventArgs e)
        {
            if ((sender as BindableObject)?.BindingContext is MobileMenuItem item)
                item.DoClicked();
        }

        private void _viewModel_OnLayoutChanged(object sender, MobileMenuButtonLayoutChangedEventArgs args)
        {
            _menu.RowDefinitions.Clear();
            for (int i=0; i< args.RowCount; i++)
                _menu.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto});
        }

        public event EventHandler ItemClicked;
        
        private void _viewModel_OnItemClicked(object sender, EventArgs e)
        {
            ItemClicked?.Invoke(this, EventArgs.Empty);
        }
    }
}