using Foundation;
using Pixiview.iOS.Renderers;
using Pixiview.iOS.Services;
using Pixiview.UI;
using Pixiview.Utils;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;

[assembly: ExportRenderer(typeof(AdaptedPage), typeof(AdaptedPageRenderer))]
namespace Pixiview.iOS.Renderers
{
    public class AdaptedPageRenderer : PageRenderer
    {
        UIDeviceOrientation lastOrientation;
        NSObject observer;

        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            if (Element is AdaptedPage page)
            {
                //var mode = ForPage.GetLargeTitleDisplay(page);
                //NavigationItem.LargeTitleDisplayMode = UINavigationItemLargeTitleDisplayMode.Automatic;

                page.InitOrientation((Orientation)UIDevice.CurrentDevice.Orientation);
                page.OnLoad();
            }
        }

        protected override void Dispose(bool disposing)
        {
            if (Element is AdaptedPage page)
            {
                page.OnUnload();
            }

            base.Dispose(disposing);
        }

        public override void ViewDidAppear(bool animated)
        {
            base.ViewDidAppear(animated);

            var element = Element;
            if (element != null)
            {
                var style = EnvironmentService.ConvertStyle(Screen.GetStatusBarStyle(element));
                EnvironmentService.SetStatusBarStyle(style);
            }

            observer = UIDevice.Notifications.ObserveOrientationDidChange(ChangeOrientation);
            ChangeOrientation(null, null);
        }

        public override void ViewWillDisappear(bool animated)
        {
            if (observer != null)
            {
                observer.Dispose();
                observer = null;
            }

            base.ViewWillDisappear(animated);
        }

        void ChangeOrientation(object sender, NSNotificationEventArgs e)
        {
            var current = UIDevice.CurrentDevice.Orientation;
            if (current == UIDeviceOrientation.FaceUp || current == UIDeviceOrientation.FaceDown)
            {
                //current = UIDeviceOrientation.Portrait;
                return;
            }
            if (lastOrientation != current)
            {
                lastOrientation = current;
                if (current == UIDeviceOrientation.Portrait && UIApplication.SharedApplication.StatusBarHidden)
                {
                    var style = EnvironmentService.ConvertStyle(Screen.GetStatusBarStyle(Element));
                    if (style != UIStatusBarStyle.BlackOpaque)
                    {
                        UIApplication.SharedApplication.SetStatusBarHidden(false, true);
                    }
                }
                if (Element is AdaptedPage page)
                {
                    page.OnOrientationChanged((Orientation)lastOrientation);
                }
            }
        }
    }
}
