using Igdc.Extensions;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using StoryEngine.Core;
using System;
using System.IO;
using System.Linq;
using System.Reflection;

namespace Igdc
{
    public class AssetReader : IDisposable
    {
        private static Assembly Assembly { get; }
            = typeof(AssetReader).GetTypeInfo().Assembly;

        private Stream _stream;
        private GraphicsDevice _device;

        public AssetReader(GraphicsDevice device, string asset)
        {
            _device = device;
            var fileName = $"{asset}.";
            var resNames = Assembly.GetManifestResourceNames();
            var resName = resNames.First(r => r.Contains(fileName));
            _stream = Assembly.GetManifestResourceStream(resName);
        }

        public Texture2D ReadTexture2D() => Texture2D.FromStream(_device, _stream);

        public History ReadHistory()
        {
            using (var reader = new StreamReader(_stream))
                return History.Deserialize(reader.ReadToEnd());
        }

        public Point[,] ReadMap()
        {
            using (var reader = new StreamReader(_stream))
                return reader.ReadToEnd().FromJson<MapDto>().ToMap();
        }

        public void Dispose() => _stream?.Dispose();
    }

    public static class GraphicsDeviceExt
    {
        public static Texture2D ReadTexture2D(this GraphicsDevice device, string asset)
        {
            using (var reader = new AssetReader(device, asset))
                return reader.ReadTexture2D();
        }

        public static History ReadHistory(this GraphicsDevice device, string asset)
        {
            using (var reader = new AssetReader(device, asset))
                return reader.ReadHistory();
        }

        public static Point[,] ReadMap(this GraphicsDevice device, string asset)
        {
            using (var reader = new AssetReader(device, asset))
                return reader.ReadMap();
        }
    }

    public class AssemblyPointer { }
}