using ComponentFramework;
using ComponentFramework.Modules;
using FullScreenShaders.Services;
using MTV3D65;

namespace FullScreenShaders.Components.Effects
{
    [AutoLoad]
    class HighPassEffect : Component
    {
        TVShader highPassShader;

        public HighPassEffect(ICore core) : base(core) { }

        public override void Initialize()
        {
            highPassShader = Scene.CreateShader();
            highPassShader.CreateFromEffectFile("High-Pass.fx");

            Rendering.ViewportSizeChanged += () => highPassShader.SetEffectParamVector2("texelSize", Rendering.TexelSize);

            base.Initialize();
        }

        public override void PreDraw()
        {
            if (SampleState.HighPass && SampleState.Downscaling && Rendering.TempSurface != null)
            {
                Screen2DImmediate.Settings_SetTextureFilter(CONST_TV_TEXTUREFILTER.TV_FILTER_NEARESTPOINT);

                Rendering.TempSurface.BltFromRenderSurface(Rendering.PostSurface);
                Rendering.PostSurface.StartRender();

                Screen2DImmediate.Draw_FullscreenQuadWithShader(highPassShader, 0, 0, 1, 1, Rendering.TempSurface.GetTexture());

                Rendering.PostSurface.EndRender();
            }
        }

        public override void PostDraw()
        {
            if (SampleState.HighPass && !SampleState.Downscaling)
            {
                Screen2DImmediate.Settings_SetTextureFilter(CONST_TV_TEXTUREFILTER.TV_FILTER_NEARESTPOINT);

                Rendering.PostSurface.BltFromMainBuffer();

                Screen2DImmediate.Draw_FullscreenQuadWithShader(highPassShader, 0, 0, 1, 1, Rendering.PostSurface.GetTexture());
            }
        }

        public override int Order
        {
            get { return 20; }
        }

        [ServiceDependency]
        public IRendering Rendering { private get; set; }
        [ServiceDependency]
        public ISampleState SampleState { private get; set; }
    }
}
