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

public class MusicManager : MonoBehaviour
{
    public static MusicManager main;
    public AudioSource mainTrack;
    public Track[] otherTracks;
    private Entity mainEntity;
    public float musicVolume = 1.0f;

    [System.Serializable]
    public class Track {
        public Emotion.types emotion;
        public AudioSource audioSource;
    }

    private void Awake() {
        if (enabled) {
            main = this;
        }
    }

    // Start is called before the first frame update
    void Start()
    {
    }

    public void OnDestroy() {
        main = null;
    }

    // Update is called once per frame
    void Update()
    {
        if (mainEntity == null && ThirdPersonController.main != null) {
            mainEntity = ThirdPersonController.main.entity;
        }
        mainTrack.volume = Mathf.Lerp(mainTrack.volume, 0.5f * musicVolume, Time.deltaTime * 0.5f);
        if (mainEntity != null) {
            foreach (Track track in otherTracks) {
                AudioSource audioSource = track.audioSource;
                if (mainEntity.emotions.Contains(track.emotion) && mainEntity.parameters.currentHP > 0) {
                    audioSource.volume = Mathf.Lerp(audioSource.volume, 0.5f * musicVolume, Time.deltaTime * 0.3f);
                }
                else {
                    audioSource.volume = Mathf.Lerp(audioSource.volume, 0.0f, Time.deltaTime * 0.3f);
                }
                audioSource.timeSamples = mainTrack.timeSamples;
            }
        }
    }
}
