using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using System.Drawing;
using System.Drawing.Imaging;

namespace Common.Util
{
    // Unable to create a 'DbContext' of type 'ApiaryContext'. The exception 'The property 'Image.Tag'
    // could not be mapped because it is of type 'object', which is not a supported primitive type or a
    // valid entity type. Either explicitly map this property, or ignore it using the '[NotMapped]' attribute
    // or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.' was thrown while attempting to create an
    // instance.
    // For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728
    public class ImageToBytesConverter : ValueConverter<Image, byte[]>
    {
        public ImageToBytesConverter() : base (
            img => ImageToBytes(img),
            bytes => BytesToImage(bytes))
            { }

        private static byte[] ImageToBytes(Image img)
        {
            using var ms = new MemoryStream();
            img.Save(ms, ImageFormat.Png);
            return ms.ToArray();
        }

        private static Image BytesToImage(byte[] bytes)
        {
            if (bytes == null || bytes.Length == 0)
            {
                return null;
            }

            using var ms = new MemoryStream(bytes);
            return Image.FromStream(ms);
        }
    }
}
