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

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

    [Tooltip("Darkest color.")]
    public ColorParameter darkest = new ColorParameter(new Color(0.11f, 0.21f, 0.08f));

    [Tooltip("Second darkest color.")]
    public ColorParameter dark = new ColorParameter(new Color(0.24f, 0.38f, 0.21f));

    [Tooltip("Second lightest color.")]
    public ColorParameter light = new ColorParameter(new Color(0.57f, 0.67f, 0.21f));

    [Tooltip("Lightest color.")]
    public ColorParameter lightest = new ColorParameter(new Color(0.75f, 0.82f, 0.46f));

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

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

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

        m_Material.SetColor("_GBDarkest", darkest.value);
        m_Material.SetColor("_GBDark", dark.value);
        m_Material.SetColor("_GBLight", light.value);
        m_Material.SetColor("_GBLightest", lightest.value);

        m_Material.SetTexture("_InputTexture", source);
        HDUtils.DrawFullScreen(cmd, m_Material, destination);
    }

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