using SkiaSharp.Views.Forms;
using System;
using System.Collections.Generic;
using System.Text;
using Xamarin.Forms;

namespace DataDisplay.Controls
{
    public class CanvasView : SKCanvasView
    {
        public static readonly BindableProperty RendererProperty = BindableProperty.Create(
            nameof(Renderer),
            typeof(Renderers.IRenderer),
            typeof(CanvasView),
            null,
            defaultBindingMode: BindingMode.TwoWay,
            propertyChanged: (bindable, oldValue, newValue) =>
            {
                ((CanvasView)bindable).RendererChanged((Renderers.IRenderer)oldValue, (Renderers.IRenderer)newValue);
            });

        // callback appelée lors de la modificiation de la propriété "Renderer"
        void RendererChanged(Renderers.IRenderer currentRenderer, Renderers.IRenderer newRenderer)
        {
            if (currentRenderer != newRenderer)
            {
                // détacher l'événement de l'ancien renderer
                if (currentRenderer != null)
                    currentRenderer.RefreshRequested -= Renderer_RefreshRequested;

                // attacher l'événement du nouveau renderer
                if (newRenderer != null)
                    newRenderer.RefreshRequested += Renderer_RefreshRequested;

                // rafraichir le contrôle
                InvalidateSurface();
            }
        }

    // Causes refreshing during an event triggered by the ISKRenderer interface
    void Renderer_RefreshRequested(object sender, EventArgs e)
        {
            InvalidateSurface();
        }

        protected override void OnPaintSurface(SKPaintSurfaceEventArgs e)
        {
           if (null == Renderer) return;
           Renderer.PaintSurface(e.Surface, e.Info);
        }

        public Renderers.IRenderer Renderer
        {
            get { return (Renderers.IRenderer)GetValue(RendererProperty); }
            set { SetValue(RendererProperty, value); }
        }
    }
}
