﻿using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Rendering.HighDefinition;
using System;

[Serializable, VolumeComponentMenu("Post-processing/Snapshot Pro (HDRP)/SobelNeon")]
public sealed class SobelNeon : CustomPostProcessVolumeComponent, IPostProcessComponent
{
    [Tooltip("Enable the effect?")]
    public BoolParameter enabled = new BoolParameter(false);

    [Tooltip("Saturation values lower than this will be clamped to this.")]
    public ClampedFloatParameter saturationFloor = new ClampedFloatParameter(0.75f, 0.0f, 1.0f);

    [Tooltip("Lightness/value values lower than this will be clamped to this.")]
    public ClampedFloatParameter lightnessFloor = new ClampedFloatParameter(0.75f, 0.0f, 1.0f);

    Material m_Material;

    public bool IsActive() => m_Material != null && enabled.value;

    // Remember to add this post process in the Custom Post Process Orders list 
    // (Project Settings > HDRP Default Settings).
    public override CustomPostProcessInjectionPoint injectionPoint => 
        CustomPostProcessInjectionPoint.AfterPostProcess;

    const string kShaderName = "SnapshotProHDRP/SobelNeon";

    public override void Setup()
    {
        if (Shader.Find(kShaderName) != null)
        {
            m_Material = new Material(Shader.Find(kShaderName));
        }
        else
        {
            Debug.LogError($"Unable to find shader '{kShaderName}' for the SobelNeon effect.");
        }
    }

    public override void Render(CommandBuffer cmd, HDCamera camera, RTHandle source, RTHandle destination)
    {
        if (m_Material == null)
        {
            return;
        }

        m_Material.SetFloat("_SaturationFloor", saturationFloor.value);
        m_Material.SetFloat("_LightnessFloor", lightnessFloor.value);

        m_Material.SetTexture("_InputTexture", source);

        HDUtils.DrawFullScreen(cmd, m_Material, destination);
    }

    public override void Cleanup()
    {
        CoreUtils.Destroy(m_Material);
    }
}
