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

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

    [Tooltip("The noise pattern to use for dithering.")]
    public TextureParameter noiseTex = new TextureParameter(null);

    [Tooltip("The size of the noise pattern.")]
    public ClampedFloatParameter noiseSize = new ClampedFloatParameter(1.0f, 0.1f, 100.0f);

    [Tooltip("The color to use for dark areas of the image.")]
    public ColorParameter darkColor = new ColorParameter(Color.black);

    [Tooltip("The color to use for light areas of the image.")]
    public ColorParameter lightColor = new ColorParameter(Color.white);

    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/Dither";

    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 Dither effect.");
        }  
    }

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

        if(noiseTex.value != null)
        {
            m_Material.SetTexture("_NoiseTex", noiseTex.value);
        }
        else
        {
            m_Material.SetTexture("_NoiseTex", Texture2D.whiteTexture);
        }

        m_Material.SetFloat("_NoiseSize", noiseSize.value);
        m_Material.SetColor("_DarkColor", darkColor.value);
        m_Material.SetColor("_LightColor", lightColor.value);
        
        m_Material.SetTexture("_InputTexture", source);
        HDUtils.DrawFullScreen(cmd, m_Material, destination);
    }

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