using System.ComponentModel;
using Billing.iOS.Renderers;
using Billing.UI;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;

[assembly: ExportRenderer(typeof(TintImageButton), typeof(TintImageButtonRenderer))]
namespace Billing.iOS.Renderers
{
    public class TintImageButtonRenderer : ImageButtonRenderer
    {
        protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            base.OnElementPropertyChanged(sender, e);

            if (Control == null)
            {
                return;
            }

            if (e.PropertyName == nameof(Image.Source) ||
                e.PropertyName == TintHelper.TintColor)
            {
                var img = Control.ImageForState(UIControlState.Normal);
                if (img != null && Element is TintImageButton image)
                {
                    Control.SetImage(img.ImageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate), UIControlState.Normal);
                    Control.TintColor = TintHelper.GetTintColor(image)?.ToUIColor();
                }
            }
        }

        protected override void OnElementChanged(ElementChangedEventArgs<ImageButton> e)
        {
            base.OnElementChanged(e);

            if (Control != null && Element is TintImageButton image)
            {
                var img = Control.ImageForState(UIControlState.Normal);
                if (img != null)
                {
                    Control.SetImage(img.ImageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate), UIControlState.Normal);
                    Control.TintColor = TintHelper.GetTintColor(image)?.ToUIColor();
                }
            }
        }
    }
}
