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

namespace Framefield.Core.ID10784262_b8dd_4af1_95db_54046d6c6972
{
    public class Class_Layer2d : OperatorPart.Function
    {
        class Renderer : BaseRenderer
        {
        }
    
        public Class_Layer2d()
        {
            try {
                using (var bytecode = ShaderBytecode.CompileFromFile("assets-common/fx/Layer2d.fx", "fx_5_0", ShaderFlags.Debug, EffectFlags.None, null, null))
                    _effect = new Effect(D3DDevice.Device, bytecode);
            }
            catch (Exception e) {
                Logger.Error(this,"error loading laye2d fx: {0} ", e.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 Image = inputs[0].Eval(context).Image; if (Image == null) return context;
            var MultiplyColor = Utilities.EvaluateVector4(context, inputs, 1);

            var subContext = new OperatorPartContext(context);
            subContext.Effect = _effect;
            subContext.Renderer = _renderer;
            subContext.InputLayout = context.Renderer.ScreenQuadInputLayout;
            subContext.CameraProjection = Matrix.OrthoLH(1, 1, -100, 100);
            subContext.WorldToCamera = Matrix.LookAtLH(new Vector3(0, 0, -5), new Vector3(0, 0, 0), new Vector3(0, 1, 0));
            subContext.ObjectTWorld = Matrix.Identity;

            using (var textureView = new ShaderResourceView(context.D3DDevice, Image))
            {
                _effect.GetVariableByName("hasDepth").AsScalar().Set(false);
                _effect.GetVariableByName("multiplyColor").AsVector().Set(MultiplyColor);

                var depthStencilDescription = new DepthStencilStateDescription();
                depthStencilDescription.IsDepthEnabled = false;
                using (var depthStencilState = new DepthStencilState(context.D3DDevice, depthStencilDescription))
                {
                    subContext.DepthStencilState = depthStencilState;
                    subContext.Texture0 = textureView;
                    subContext.Renderer.SetupEffect(subContext);
    
                    subContext.Renderer.Render(subContext.Renderer._screenQuadMesh, subContext);
                }
            }

            return context;
        }

        Effect _effect;
        Renderer _renderer = new Renderer();
    }
}

