#if UNITY_5_3_OR_NEWER
#define NOESIS
using Noesis;
using UnityEngine;
using TextureFormat = UnityEngine.TextureFormat;
#else
using System;
using System.Windows.Media;
using System.Windows.Media.Imaging;
#endif
using System.IO;
using Path = System.IO.Path;

namespace BindingMemoryLeak
{
    public static class LoadImage
    {


        /// <summary>
        /// Load an image in Content folder
        /// </summary>
        /// <param name="folderName"></param>
        /// <param name="fileName"></param>
        public static ImageSource GetImageSource(string folderName, string fileName)
        {
            var filePath = Path.Combine("Content", folderName, fileName);
#if USE_STREAMING_DATA_PATH
            filePath = Path.Combine(Application.streamingAssetsPath, filePath);
#endif

            if (!File.Exists(filePath))
            {
                return null;
            }

#if NOESIS
            var fileData = File.ReadAllBytes(filePath);
            var tex = new Texture2D(2, 2, TextureFormat.RGBA32, true);
            tex.LoadImage(fileData); 

            return new TextureSource(tex);

#else
            return new BitmapImage(new Uri(filePath)); //this will fail in WPF if we disable mod manager.
#endif
        }

        /// <summary>
        /// Load an image in Content folder
        /// </summary>
        /// <param name="folderName"></param>
        /// <param name="fileName"></param>
        public static ImageSource GetImageSource(string folderName, string fileName, bool mipmap)
        {
            var filePath = Path.Combine("Content", folderName, fileName);
#if USE_STREAMING_DATA_PATH
            filePath = Path.Combine(Application.streamingAssetsPath, filePath);
#endif
            if (!File.Exists(filePath))
            {
                return null;
            }

#if NOESIS
            var fileData = File.ReadAllBytes(filePath);
            var tex = new Texture2D(2, 2, TextureFormat.RGBA32, mipmap);
            tex.LoadImage(fileData); 

            return new TextureSource(tex);

#else
            return new BitmapImage(new Uri(filePath)); //this will fail in WPF if we disable mod manager.
#endif
        }

        /// <summary>
        /// Load an image in Content folder
        /// </summary>
        /// <param name="filePath"></param>
        public static ImageSource GetImageSource(string filePath)
        {
#if USE_STREAMING_DATA_PATH
            filePath = Path.Combine(Application.streamingAssetsPath, filePath);
#endif
            if (!File.Exists(filePath))
            {
                return null;
            }

#if NOESIS
            var fileData = File.ReadAllBytes(filePath);
            var tex = new Texture2D(2, 2, TextureFormat.RGBA32, true);
            tex.LoadImage(fileData); 

            return new TextureSource(tex);

#else
            return new BitmapImage(new Uri(filePath)); //this will fail in WPF if we disable mod manager.
#endif
        }
    }
}
