using GhostSystem;
using UnityEngine;

public class RecieveHeat : MonoBehaviour
{
    public Renderer myRenderer;
    private float heatLevel; // von 0-255
    private float heatLevelNormalized; // von 0-1
    private Material myMat;

    private async void OnEnable()
    {
        GhostReplayManager.OnRestartLoop += HandleRestartLoop;
    }

    private void OnDisable()
    {
        GhostReplayManager.OnRestartLoop -= HandleRestartLoop;
    }

    private void HandleRestartLoop()
    {
        SetHeat(0);
    }

    private void Start()
    {
        if (myRenderer == null)
        {
            TryGetComponent<Renderer>(out myRenderer);
        }
        myMat = myRenderer.material;
        SetHeat(0);
    }

    public void SetHeat(float heat)
    {
        if (heat > 1f) return;
        heatLevel = heat;
        float redAmount = CalcRedAmount(heatLevel);
        myMat.color = new Color(redAmount,0,0);
    }

    public void AddHeat(float heat)
    {
        heatLevel += heat;
        if (heatLevel > 1f) return;
        float redAmount = CalcRedAmount(heatLevel);
        Debug.Log(gameObject.ToString() + "Heat in: " + heatLevel + "Heat out: " + redAmount);
        myMat.color = new Color(redAmount, 0, 0);
    }

    private float CalcRedAmount(float xNormalized)
    {
        float y = Mathf.Pow(xNormalized, 0.5f);
        return Mathf.Clamp(y, 0f, 1f);
    }
}
