using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace PlantBox.Client.Extensions
{
    [ContentProperty(nameof(Path))]
    public class ImageResourceExtension : IMarkupExtension<ImageSource>
    {
        public string Path { get; set; }

        public static ImageSource GetImage(string name)
        {
            var assembly = Assembly.GetCallingAssembly();
            string path = $"PlantBox.Client.Resources.Images.{name}";

            if (!assembly.GetManifestResourceNames().Contains(path))
            {
#if DEBUG
                System.Diagnostics.Debug.WriteLine($"[ImageResourceExtension](Error): File '{name}' does not exist");
#else
                throw new ArgumentException($"File '{path}' does not exist");
#endif
            }

            return ImageSource.FromResource(path, assembly);
        }

        public ImageSource ProvideValue(IServiceProvider serviceProvider)
        {
            return GetImage(Path);
        }

        object IMarkupExtension.ProvideValue(IServiceProvider serviceProvider)
        {
            return (this as IMarkupExtension<ImageSource>).ProvideValue(serviceProvider);
        }
    }
}
