using UnityEngine;
using UnityEngine.UI;

public class MusicPlayer : MonoBehaviour {

    public Image MusicButton;
    public Sprite MusicOnSprite;
    public Sprite MusicOffSprite;

    private AudioSource[] music;
    private int randStart, rand;
    private string musicControl;
    private float musicVolume;

    // Use this for initialization
    void Start() {
        this.music = GetComponents<AudioSource>();
        UpdateMusicControl();
    }

    // Update is called once per frame
    void Update() {
        music[rand].volume = musicVolume;
        if (music.Length > 1) {
            PlayNext();
        } else {
            return;
        }
    }

    void PlayMusic() {
        if (music.Length > 1) {
            var rand = Random.Range(0, music.Length);
        } else {
            rand = 0;
        }
        //Debug.Log("Current track:" + music[rand].clip);
        if (!music[rand].isPlaying) {
            music[rand].volume = musicVolume;
            music[rand].Play();
            //Debug.Log("Playing: " + music[rand].clip);
        }
        randStart = rand;
    }

    void PlayNext() {
        if (!music[randStart].isPlaying) {
            var rand = Random.Range(0, music.Length);
            if (rand == randStart) {
                rand = Random.Range(0, music.Length);
            } else {
                music[rand].volume = musicVolume;
                music[rand].Play();
                randStart = rand;
            }
        }
    }

    public void PlayControl() {
        if (musicControl == "On") {
            PlayerPrefs.SetString("Music", "Off");
            
            musicVolume = 0.0f;
        } else {
            PlayerPrefs.SetString("Music", "On");
            
            musicVolume = 0.3f;
        }
        UpdateMusicControl();
    }

    private void UpdateMusicControl() {
        musicControl = PlayerPrefs.GetString("Music", "On");
        if (musicControl == "On") {
            musicVolume = 0.3f;
            if (MusicButton != null) {
                MusicButton.sprite = MusicOffSprite;
            }
        } else {
            musicVolume = 0.0f;
            if (MusicButton != null) {
                MusicButton.sprite = MusicOnSprite;
            }
        }

        PlayMusic();
    }
}
