package de.pneugebala.pdx.utils.assets;

import java.util.ArrayList;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.audio.Music;

import de.pneugebala.pdx.exceptions.PdxAlreadyLoadedException;
import de.pneugebala.pdx.exceptions.PdxNotFoundException;
import de.pneugebala.pdx.exceptions.PdxNotLoadedException;

public class PdxMusic {

	private static boolean isLoaded = false;
	private static boolean isDisposed = false;
	
	private static ArrayList<Music> objectList;
	private static ArrayList<String> nameList;
	
	private static ArrayList<String> loaderMusicPathList;
	private static ArrayList<String> loaderMusicNameList;
	
	public PdxMusic() {
		objectList = new ArrayList<Music>();
		nameList = new ArrayList<String>();
		loaderMusicPathList = new ArrayList<String>();
		loaderMusicNameList = new ArrayList<String>();
	}
	
	/**
	 * Loads all music instances added to the music loader.
	 * Only works when this method hasn't been called before.
	 */
	public void load() {
		if(!isDisposed) {
			if(!isLoaded) {
				for(int i = 0; i < loaderMusicPathList.size(); i++) {
					objectList.add(Gdx.audio.newMusic(Gdx.files.internal(loaderMusicPathList.get(i))));
					nameList.add(loaderMusicNameList.get(i));
				}
				isLoaded = true;
			} else {
				throw new PdxAlreadyLoadedException("Music instances already loaded!");
			}
		}
	}
	
	/**
	 * Add a music instance with the desired name to the music loader.
	 * Only works when the {@link #load()} method hasn't been called before.
	 * @param path
	 * @param name
	 */
	public void addMusic(String path, String name) {
		if(!isDisposed) {
			if(!isLoaded) {
				loaderMusicPathList.add(path);
				loaderMusicNameList.add(name);
			} else {
				throw new PdxAlreadyLoadedException("Music instances already loaded!");
			}
		}
	}
	
	/**
	 * Get the music instance bound to the given name.
	 * Only works when the {@link #load()} method has been called before.
	 * @param name
	 * @return texture
	 */
	public Music getMusic(String name) {
		if(!isDisposed) {
			if(isLoaded) {
				Music music = null;
				for(int i = 0; i < nameList.size(); i++) {
					if(nameList.get(i).equals(name)) {
						music = objectList.get(i);
					}
				}
				if(music == null) {
					throw new PdxNotFoundException("Music instance with the given name not found!");
				}
				return music;
			} else {
				throw new PdxNotLoadedException("Music instances not loaded!");
			}
		} else {
			return null;
		}
	}
	
	/**
	 * This is called automatically. Do not call it yourself!
	 */
	public void dispose() {
		isDisposed = false;
		for(Music music : objectList) {
			music.dispose();
		}
		objectList.clear();
		nameList.clear();
		loaderMusicPathList.clear();
		loaderMusicNameList.clear();
	}
	
}
