using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GlowOnHover : MonoBehaviour
{
    public float hoverIntensity, defaultIntensity, lerpSpeed = 1;
    public AudioClip hoverSound;
    public Renderer target;
    private float fromIntensity, toIntensity, currentIntensity, t;
    private Material material;
    private Color defaultColor;
    private AudioSource audioSource;
    private void Start()
    {
        this.material = this.target.material;
        this.defaultColor = material.GetColor("_EmissionColor");
        this.toIntensity = defaultIntensity;
        this.audioSource = GetComponent<AudioSource>();
    }

    private void Update()
    {

        this.currentIntensity = Mathf.Lerp(this.fromIntensity, this.toIntensity, this.t);
        this.t += Time.deltaTime * this.lerpSpeed;

        Color finalColor = this.defaultColor * Mathf.LinearToGammaSpace(this.currentIntensity);
        this.material.SetVector("_EmissionColor", this.defaultColor * this.currentIntensity);

       //this.material.SetColor("_EmissionColor", finalColor);

    }

    private void lerpEmission(float from, float to)
    {
        this.t = 0;
        this.fromIntensity = from;
        this.toIntensity = to;
    }

    private void OnMouseEnter()
    {
        this.lerpEmission(this.currentIntensity, this.hoverIntensity);
        if (this.hoverSound && this.audioSource)
        {
            this.audioSource.PlayOneShot(this.hoverSound);
        }
    }

    private void OnMouseExit()
    {
        this.lerpEmission(this.currentIntensity, this.defaultIntensity);
    }
}
