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

public class AudioSystem : MonoBehaviour {
    static AudioSystem _inst;
    public int channels = 16;
    int channel = 0;

    AudioSourceX [] sources;

    [SerializeField] AudioSource musicSource;
    [SerializeField] Transform defTarget;

    static public AudioSystem inst {
        get {
            if(_inst == null) _inst = FindObjectOfType<AudioSystem>();
            return _inst;
        }
    }

    private void Awake() {
        CreateSources();
    }

    void CreateSources() {
        sources = new AudioSourceX[channels];
        Transform transf = transform;

        for(int i = 0; i < sources.Length; i++) {
            sources[i] = AudioSourceX.Create("Channel " + i, transf);
        }
    }

    AudioSourceX asBuf;

    public void PlaySound(GameSound sound) {
        PlaySound(sound, defTarget.position);
    }

    public void PlaySound(GameSound sound, Vector3 pos) {
        asBuf = sources[channel];

        asBuf.source.clip = sound.clip;
        asBuf.source.pitch = sound.pitch;
        asBuf.source.volume = sound.volume;
        asBuf.transf.position = pos;
        asBuf.source.Play();

        channel = (channel + 1) % channels;
    }
    
    public void PlayMusic(AudioClip clip) {
        musicSource.clip = clip;
        musicSource.Play();
    }
}
