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

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

            private readonly LayerMask _layer;
            private readonly Material _overwriteMaterial;

            public RenderPass(LayerMask layer, Material overwriteMaterial, RenderPassEvent renderPassEvent)
            {
                _layer = layer;
                _overwriteMaterial = overwriteMaterial;
                
                this.renderPassEvent = renderPassEvent;
                _renderStateBlock = new RenderStateBlock(RenderStateMask.Nothing);
            }

            public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData)
            {
                var sortingCriteria = renderingData.cameraData.defaultOpaqueSortFlags;
                var drawingSettings =
                    CreateDrawingSettings(
                        new List<ShaderTagId>
                        {
                            new("SRPDefaultUnlit"), new("UniversalForward"), new("UniversalForwardOnly")
                        },
                        ref renderingData, sortingCriteria);
                if (_overwriteMaterial)
                {
                    drawingSettings.overrideMaterial = _overwriteMaterial;
                }

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

        private RenderPass _renderPass;

        public LayerMask layer;
        public Material overwriteMaterial;
        public RenderPassEvent renderPassEvent = RenderPassEvent.AfterRenderingOpaques;

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

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