using System;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
using UIKit;
using System.Linq;
using CoreGraphics;
using System.Collections.Generic;
using System.Windows.Input;

// [assembly: Xamarin.Forms.ExportRenderer(typeof(ContentPage), typeof(InABox.Mobile.DropDownMenuRenderer))]
namespace InABox.Mobile
{

    public class DropDownMenuRenderer : PageRenderer
    {

        //I used UITableView for showing the menulist of secondary toolbar items.
        List<ToolbarItem> _secondaryItems;
        UITableView table;

        protected override void OnElementChanged(VisualElementChangedEventArgs e)
        {
            //Get all secondary toolbar items and fill it to the gloabal list variable and remove from the content page.
            if (e.NewElement is ContentPage page)
            {
                _secondaryItems = page.ToolbarItems.Where(i => i.Order == ToolbarItemOrder.Secondary).ToList();
                _secondaryItems.ForEach(t => page.ToolbarItems.Remove(t));
            }
            base.OnElementChanged(e);
        }

        public override void ViewWillAppear(bool animated)
        {
            var element = (ContentPage)Element;
            //If global secondary toolbar items are not null, I created and added a primary toolbar item with image(Overflow) I         
            // want to show.

            if (_secondaryItems != null && _secondaryItems.Count > 0)
            {
                element.ToolbarItems.Clear();
                element.ToolbarItems.Add(new ToolbarItem()
                {
                    Order = ToolbarItemOrder.Primary,
                    Text = "Tools",
                    //Icon = "more.png",
                    Priority = 1,
                    Command = new Command(() =>
                    {
                        ToolClicked();
                    })
                });
            }
            base.ViewWillAppear(animated);
        }

        //Create a table instance and added it to the view.
        private void ToolClicked()
        {
            if (table == null)
            {
                var items = _secondaryItems.Where(x => (!(x is HideableToolbarItem)) || (((HideableToolbarItem)x).IsVisible)).ToList();

                //Set the table position to right side. and set height to the content height.
                var childRect = new CGRect((float)View.Bounds.Width - 250, 0, 250, items.Count() * 56);
                table = new UITableView(childRect)
                {
                    Source = new DropDownMenuSource(items) 
                };
                Add(table);
                return;
            }
            foreach (var subview in View.Subviews)
            {
                if (subview == table)
                {
                    table.RemoveFromSuperview();
                    return;
                }
            }
            Add(table);
        }

    }
}
