using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace MonoGame.FourEngine.Resources
{
    /// <summary>
    /// Texture resource
    /// </summary>
    public class Texture : IResource
    {
        /// <summary>
        /// Permanent resources are not deleted on ResourceManager.Clear
        /// </summary>
        public bool Permanent { get; protected set; }

        /// <summary>
        /// Texture data
        /// </summary>
        public Texture2D Data { get; }

        /// <summary>
        /// Dimensions of Texture
        /// </summary>
        public Point Size { get; }

        /// <summary>
        /// Create new Texture instance
        /// </summary>
        /// <param name="def">Texture parameters</param>
        public Texture(TextureDefinition def)
        {
            Data = ReadTexture2D(def.FileName);
            Data.Name = def.FileName;
            Size = Data.Bounds.Size;
        }

        /// <summary>
        /// Create new Texture instance
        /// </summary>
        /// <param name="fileName">Texture file name</param>
        public Texture(string fileName) : this(new TextureDefinition { FileName = fileName })
        { }

        private Texture2D ReadTexture2D(string fileName)
        {
            using (var stream = ServiceLocator.ResourceLoader.GetStream(fileName))
                return Texture2D.FromStream(FourEngineGame.Current.GraphicsDevice, stream);
        }

        public void Dispose()
            => Data?.Dispose();

        // Make it convertable to Texture2D for easier interop with MonoGame
        public static implicit operator Texture2D(Texture texture)
            => texture.Data;
    }

    /// <summary>
    /// Defines Texture parameters
    /// </summary>
    public class TextureDefinition : IResourceDefinition
    {
        /// <summary>
        /// Texture file name
        /// </summary>
        public string FileName { get; set; }
    }
}