using System.Linq;
using Windows.UI;
using Windows.UI.Xaml;
using Xamarin.Forms.Platform.UWP;
using CC = CartesianChartXF_1171097.Portable;

[assembly: Xamarin.Forms.ResolutionGroupName(CC.GradientBarEffect.YourCompanyName)]
[assembly: Xamarin.Forms.ExportEffect(typeof(CartesianChartXF_1171097.UWP.GradientBarEffect), CC.GradientBarEffect.GradientBarEffectName)]

namespace CartesianChartXF_1171097.UWP
{
    public class GradientBarEffect : PlatformEffect
    {
        protected override void OnAttached()
        {
            CC.GradientBarEffect effect = (CC.GradientBarEffect)this.Element.Effects.First(e => e is CC.GradientBarEffect);
            var chart = (Telerik.UI.Xaml.Controls.Chart.RadCartesianChart)this.Control;

            foreach (var series in chart.Series)
            {
                var barSeries = series as Telerik.UI.Xaml.Controls.Chart.BarSeries;
                if (barSeries != null)
                {
                    barSeries.PointTemplate = this.GetGradientBarTemplate(effect);
                }
            }
        }

        protected override void OnDetached()
        {
        }

        private DataTemplate GetGradientBarTemplate(CC.GradientBarEffect effect)
        {
            Color startColor = ToWinColor(effect.StartColor);
            Color endColor = ToWinColor(effect.EndColor);

            string xamlString = @"
<DataTemplate xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation"">
    <Border>
        <Border.Background>
            <LinearGradientBrush StartPoint=""0.5, 1"" EndPoint=""0.5, 0"">
                <GradientStop Offset=""0"" Color=""" + startColor + @""" />
                <GradientStop Offset=""1"" Color=""" + endColor + @""" />
            </LinearGradientBrush>
        </Border.Background>
    </Border>
</DataTemplate>";

            return (DataTemplate)Windows.UI.Xaml.Markup.XamlReader.Load(xamlString);
        }

        private Color ToWinColor(Xamarin.Forms.Color xfColor)
        {
            return Color.FromArgb((byte)(xfColor.A * 255), (byte)(xfColor.R * 255), (byte)(xfColor.G * 255), (byte)(xfColor.B * 255));
        }
    }
}
