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

public class Audio : MonoBehaviour {

    public AudioClip click_simple = null;
    public AudioClip plant = null;
    public AudioClip pop = null;
    public AudioClip walk_grass = null;
    public AudioClip bite = null;
    public AudioClip cash = null;

    private List<AudioSource> m_sources = new List<AudioSource>( );

    private static Audio ms_instance = null;
    private float m_sfxVolume = 1.0f;

    void Awake( ) {
        ms_instance = this;
    }

    public static Audio get( ) {
        return ms_instance;
    }

    public static void setSfxVolume( float volume ) {

        ms_instance.m_sfxVolume = volume;

        for ( int i = 0; i < ms_instance.m_sources.Count; i++ ) {

            AudioSource s = ms_instance.m_sources[ i ];

            if ( !s.loop ){
                s.volume = ms_instance.m_sfxVolume;
            }
        }
    }

    public static AudioSource getSource( ) {

        AudioSource result = null;

        for ( int i = 0; i < ms_instance.m_sources.Count; i++ ) {

            if ( !ms_instance.m_sources[ i ].isPlaying ) {
                result = ms_instance.m_sources[ i ];
                break;
            }
        }

        if ( result == null && ms_instance.m_sources.Count < 20 ) {
            result = ms_instance.gameObject.AddComponent<AudioSource>( );
            result.playOnAwake = false;
            ms_instance.m_sources.Add( result );
        }

        return result;
    }

    public static void play( AudioClip clip, float volume = 1.0f, bool loop = false ) {

        AudioSource source = getSource( );

        if ( source != null ) {
            source.loop = loop;
            source.volume = ms_instance.m_sfxVolume * volume;
            source.clip = clip;
            source.Play( );
        }
    }
}
