using System;
using Syncfusion.XForms.PopupLayout;
using Xamarin.Forms;

namespace InABox.Mobile
{
    public abstract class MobileView<TViewModel> : BaseMobileView 
        where TViewModel : class, IMobileViewModel
    {
        private static readonly BindableProperty ViewModelProperty =
            BindableProperty.Create(
                nameof(ViewModel), 
                typeof(TViewModel), 
                typeof(MobileView<TViewModel>), 
                null
            );
        
        public TViewModel ViewModel
        {
            get => (TViewModel)GetValue(ViewModelProperty);
            set
            {
                if (ViewModel != null)
                    ViewModel.Loaded -= ViewModel_OnLoaded;
                
                SetValue(ViewModelProperty,value);                
                
                if (ViewModel != null)
                    ViewModel.Loaded += ViewModel_OnLoaded;
            }
        }

        private bool _loaded = false;
        
        protected override void DoBindingContextChanged()
        {
            ViewModel = BindingContext as TViewModel;
            Refresh();
            _loaded = ViewModel != null;
        }
        
        public void RefreshBindings()
        {
            var model = ViewModel;
            BindingContext = null;
            BindingContext = model;
        }
        
        private void ViewModel_OnLoaded(object sender, MobileViewModelLoadedEventArgs args)
        {
            Refresh();
        }

        public abstract void Refresh();
        
        public event MobileViewChangedEvent Changed;

        protected void DoChanged(string property)
        {
            if (_loaded)
                Changed?.Invoke(this, new MobileViewChangedEventArgs(property));
        }

        private readonly SfPopupLayout _popup = new SfPopupLayout();
        
        protected void ShowPopup(Func<View> view, int height = -1, int width = -1, int padding = 10)
        {
            _popup.PopupView.HeightRequest = height == -1 ? Application.Current.MainPage.Height * 0.8 : height;
            _popup.PopupView.WidthRequest = width == -1 ? Application.Current.MainPage.Width * 0.8 : width;
            _popup.PopupView.ShowHeader = false;
            _popup.PopupView.ShowFooter = false;
            _popup.PopupView.ContentTemplate = new DataTemplate(() =>
            {
                Grid grid = new Grid() { Margin = padding, Padding = padding};
                grid.Children.Add(view());
                return grid;
            });
            _popup.Show();
        }

        protected void DismissPopup()
        {
            _popup.Dismiss();
        }
    }
}