using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;

namespace EscapeRoomEngine.Portal.Runtime
{
    public class RenderPortalSurface : ScriptableRendererFeature
    {
        private class RenderPass : ScriptableRenderPass
        {
            private RenderStateBlock _renderStateBlock;

            private readonly LayerMask _layer;

            public RenderPass(LayerMask layer)
            {
                _layer = layer;
                
                renderPassEvent = RenderPassEvent.BeforeRenderingTransparents;
                _renderStateBlock = new RenderStateBlock(RenderStateMask.Nothing);
            }

            public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData)
            {
                var drawingSettings =
                    CreateDrawingSettings(
                        new List<ShaderTagId>
                        {
                            new("SRPDefaultUnlit"), new("UniversalForward"), new("UniversalForwardOnly")
                        },
                        ref renderingData, SortingCriteria.CommonTransparent);

                var filteringSettings = new FilteringSettings(RenderQueueRange.transparent, _layer);
                context.DrawRenderers(renderingData.cullResults, ref drawingSettings, ref filteringSettings, ref _renderStateBlock);
            }
        }

        private RenderPass _renderPass;

        public LayerMask layer;

        public override void Create()
        {
            _renderPass = new RenderPass(layer);
        }

        public override void AddRenderPasses(ScriptableRenderer renderer, ref RenderingData renderingData)
        {
            renderer.EnqueuePass(_renderPass);
        }
    }
}