//>>> _using
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SharpDX;
using SharpDX.Direct3D11;
using SharpDX.Windows;
//<<< _using
using System.Dynamic;

namespace Framefield.Core.ID3ebbf2a6_8058_4729_969c_6f864cfa5744
{
    public class Class_MemoryAsImage : OperatorPart.Function
    {
        //>>> _inputids
        private enum InputId
        {
            Binary = 0
        }
        //<<< _inputids

        //>>> _outputids
        private enum OutputId
        {
            Image = 0,
            SizeX = 1,
            SizeY = 2
        }
        //<<< _outputids

        public override void Dispose()
        {
            Utilities.DisposeObj(ref _image);
        }

        public override OperatorPartContext Eval(OperatorPartContext context, List<OperatorPart> inputs, int outputIdx) 
        {
            //>>> __params
            var Binary = inputs[(int)InputId.Binary].Eval(context).Dynamic;
            //<<< __params

             if (Binary == null)
             {
                context.Image = null;
                return context;
             }
 
            if (Changed)
            {
                Dispose();
                try
                {
                    _image = SharpDX.Direct3D11.Resource.FromMemory<Texture2D>(D3DDevice.Device, Binary.Data);
                    _size = new Vector2(_image.Description.Width, _image.Description.Height); 
                }
                catch (Exception e)
                {
                    Logger.Error(this, "binary data could not be treated as image: {0}", e.Message);
                    _image = null;
                } 

                Changed = false;
            }

            if (_image != null)
            {
                switch ((OutputId)outputIdx)
                {
                    case OutputId.Image:
                        context.Image = _image;
                        break;
                    case OutputId.SizeX:
                        context.Value = _size.X;
                        break;
                    case OutputId.SizeY:
                        context.Value = _size.Y;
                        break;
                }
            }
            else
            {
                switch (outputIdx)
                {
                    case (int)OutputId.Image:
                        context.Image = null;
                        break;
                    case (int)OutputId.SizeX:
                        context.Value = 0;
                        break;
                    case (int)OutputId.SizeY:
                        context.Value = 0;
                        break;
                }
            }

            return context;
        }

        Texture2D _image;
        Vector2 _size;
    }
}

