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

public class AddShadow : MonoBehaviour
{
    public Camera SceneCam;
    public Light PointLight;

    private Camera shadowCam;

    public Shader PostShader;

    private List<Light> lights;

    // Start is called before the first frame update
    void Start()
    {
        lights = FindObjectsOfType<Light>().ToList();
        shadowCam = GetComponent<Camera>();

        Camera.onPreCull += CamPreCull;
        Camera.onPreRender += CamPreRender;
        Camera.onPostRender += CamPostRender;
    }

    private void CamPreRender(Camera cam)
    {
        Debug.Log("CamPreRender " + cam.name);
    }

    private void CamPostRender(Camera cam)
    {
        Debug.Log("CamPostRender " + cam.name);
    }

    private void CamPreCull(Camera cam)
    {
        Debug.Log("CamPreCull " + cam.name);
    }

    private AmbientMode cacheAmbientMode;
    private Color cacheAmbientSkyColor;
    private float cacheAmbientIntensity;
    private Material cacheSkybox;
    void OnPreCull()
    {
        Debug.Log("Shadow PreCull");
        //Debug.Log("PRE " + (Camera.current == shadowCam));
        //lights.ForEach(l => l.enabled = false);

        PointLight.enabled = true;

        cacheAmbientMode = RenderSettings.ambientMode;
        cacheSkybox = RenderSettings.skybox;
        cacheAmbientSkyColor = RenderSettings.ambientSkyColor;
        cacheAmbientIntensity = RenderSettings.ambientIntensity;

        RenderSettings.ambientMode = AmbientMode.Flat;
        RenderSettings.skybox = null;
        RenderSettings.ambientSkyColor = new Color(0, 0, 0, 1);
        RenderSettings.ambientIntensity = 0;
    }

    void OnPostRender()
    {
        Debug.Log("Shadow PostRender");
        PointLight.enabled = false;
        //Debug.Log("POST " + (Camera.current == shadowCam));
        //PointLight.enabled = false;
        //lights.ForEach(l => l.enabled = true);


        RenderSettings.ambientMode = cacheAmbientMode;
        RenderSettings.skybox = cacheSkybox;
        RenderSettings.ambientSkyColor = cacheAmbientSkyColor;
        RenderSettings.ambientIntensity = cacheAmbientIntensity;
    }

    // Update is called once per frame
    void Update()
    {
        shadowCam.enabled = PointLight != null;
        if (shadowCam.enabled)
        {
            shadowCam.CopyFrom(SceneCam);
            shadowCam.depth = 1;
            shadowCam.clearFlags = CameraClearFlags.Depth;
            shadowCam.SetReplacementShader(PostShader, "");
            shadowCam.cullingMask = ~(LayerMask.GetMask("Virus") | LayerMask.GetMask("Player") | LayerMask.GetMask("NoShadow"));
        }
    }
}
