namespace inutralia
{
    using System;
    using System.Collections.Generic;
    using System.Globalization;
    using System.Linq;
    using Xamarin.Forms;

    class AlternatingBackgroundColorConverter : IValueConverter
    {
        private List<Color> _Colors;

        public AlternatingBackgroundColorConverter(string commaSeparatedColors)
        {
            var conv = new ColorTypeConverter();

            string[] colors = commaSeparatedColors.Split(',');

            _Colors = new List<Color>();

            foreach (string s in colors)
            {
                try
                {
                    if (s.Length > 0)
                        _Colors.Add((Color)conv.ConvertFromInvariantString(s));
                }
                catch (Exception)
                { }
            } //endforeach
        }

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            // Si no hay lista de colores o los parámetros no son correctos => transparente
            if ((value == null) || (parameter == null) || (_Colors.Count < 1))
                return Color.Transparent;

            // Obtener índice del elemento en la lista
            var index = ((ListView)parameter).ItemsSource.Cast<object>().ToList().IndexOf(value);

            // Retornar el color que corresponda
            return _Colors[index % _Colors.Count];
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}
