using System;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;

namespace RebootKit.Engine.Graphics.Pixelize {
    public class PixelizePass : ScriptableRenderPass {
        static readonly int PixelBufferID = Shader.PropertyToID("_PixelBuffer");

        RenderTargetIdentifier _colorBuffer;
        int _frameHeight;
        int _frameWidth;

        readonly Material _material;
        RenderTargetIdentifier _pixelBuffer;

        readonly PixelizeFeature.PassSettings _settings;

        public PixelizePass(PixelizeFeature.PassSettings settings) {
            _settings = settings;
            renderPassEvent = settings.RenderPassEvent;
            _material = CoreUtils.CreateEngineMaterial("Hidden/Szafa/Pixelize");
        }

        public override void OnCameraSetup(CommandBuffer cmd, ref RenderingData renderingData) {
            _colorBuffer = renderingData.cameraData.renderer.cameraColorTargetHandle;
            RenderTextureDescriptor descriptor = renderingData.cameraData.cameraTargetDescriptor;

            _frameHeight = _settings.FrameHeight;
            _frameWidth = (int) (_frameHeight * renderingData.cameraData.camera.aspect + 0.5f);

            _material.SetVector("_BlockCount", new Vector2(_frameWidth, _frameHeight));
            _material.SetVector("_BlockSize", new Vector2(1.0f / _frameWidth, 1.0f / _frameHeight));
            _material.SetVector("_HalfBlockSize", new Vector2(0.5f / _frameWidth, 0.5f / _frameHeight));

            descriptor.height = _frameWidth;
            descriptor.width = _frameWidth;

            cmd.GetTemporaryRT(PixelBufferID, descriptor, FilterMode.Point);
            _pixelBuffer = new RenderTargetIdentifier(PixelBufferID);
        }

        public override void OnCameraCleanup(CommandBuffer cmd) {
            if (cmd == null) throw new ArgumentNullException(nameof(cmd));

            cmd.ReleaseTemporaryRT(PixelBufferID);
        }

        public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData) {
            CommandBuffer cmd = CommandBufferPool.Get();
            using (new ProfilingScope(cmd, new ProfilingSampler("Pixelize Pass"))) {
                // Blit(cmd, _colorBuffer, _pixelBuffer, _material);
                // Blit(cmd, _pixelBuffer, _colorBuffer);
            }

            context.ExecuteCommandBuffer(cmd);
            CommandBufferPool.Release(cmd);
        }
    }
}