using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using SharpDX;
using SharpDX.D3DCompiler;
using SharpDX.Direct3D11;
using SharpDX.DXGI;
using SharpDX.Windows;
using Framefield.Core.Rendering;

namespace Framefield.Core.IDa6790d44_81e9_4d90_bdca_52f0fd47b9b9
{ 
    public class Class_ObjectDisplace : OperatorPart.Function
    {
        public class Renderer : BaseRenderer
        {
            public override void SetupEffect(OperatorPartContext context) {
                base.SetupEffect(context);

                context.Effect.GetVariableByName("scale").AsVector().Set(_scale);
                context.Effect.GetVariableByName("rotate").AsVector().Set(_rotate);
                context.Effect.GetVariableByName("textureScale").AsScalar().Set(_textureScale);
            }

            public SharpDX.Vector2 _scale;
            public SharpDX.Vector2 _rotate;
            public float _textureScale;
        }

        public Class_ObjectDisplace() {
            try {
                _renderer = new Renderer();
                using (var bytecode = ShaderBytecode.CompileFromFile("assets-common/fx/ObjectDisplace.fx", "fx_5_0", ShaderFlags.None, EffectFlags.None, null, null))
                    _effect = new Effect(D3DDevice.Device, bytecode);
            }
            catch (Exception ex) {
                Logger.Error(this,"error creating effect: {0}", ex.Message);
            }
        }



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

        public override OperatorPartContext Eval(OperatorPartContext context, List<OperatorPart> inputs, int outputIdx) {
            var Scene = inputs[0];//.Eval(context);
            _renderer._scale = new SharpDX.Vector2(  inputs[1].Eval(context).Value, 
                                                    inputs[2].Eval(context).Value);

            _renderer._rotate = new SharpDX.Vector2( inputs[3].Eval(context).Value, 
                                                    inputs[4].Eval(context).Value);
                                                    
            _renderer._textureScale = inputs[5].Eval(context).Value;                                        

            var D3DDevice = context.D3DDevice;
            var subContext = new OperatorPartContext(context);
            try {
                subContext.Effect = _effect;
                subContext.InputLayout = context.Renderer.SceneDefaultInputLayout;
                subContext.Renderer = _renderer;

                Scene.Eval(subContext);
            }
            catch (Exception exception) {
                Logger.Error(this,"Load Effect error: {0}\n{1}\n{2} .", exception.Message, exception.Source, exception.InnerException);
            }

            return context;
        }

        Effect _effect;
        Renderer _renderer;
    }
}

