package zero1hd.polyjet.ui.windows;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.ui.List;
import com.badlogic.gdx.scenes.scene2d.ui.ScrollPane;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.ui.Window;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener.ChangeEvent;
import com.badlogic.gdx.utils.Array;

import zero1hd.polyjet.audio.Audio;
import zero1hd.polyjet.audio.AudioData;
import zero1hd.polyjet.util.MiniEvents;
import zero1hd.polyjet.util.MiniSender;

public class MusicSelector extends Window {
	boolean confirmed;
	boolean back;
	FileHandle selectedMusic;
	Array<String> fileNames;
	private List<String> musicList;
	private String path;
	private ScrollPane listScroller;
	public MiniSender miniSender;
	
	public MusicSelector(String title, Skin skin, final String path, String listStyle) {
		super(title, skin, "tinted");
		this.path = path;
		padTop(25f);
		padLeft(5f);
		padRight(5f);
		
		miniSender = new MiniSender();
		
		setSize(Gdx.graphics.getWidth()*0.5f, Gdx.graphics.getHeight()*0.5f);
		
		fileNames = new Array<>();
		musicList = new List<String>(skin, listStyle);
		
		TextButton confirmButton = new TextButton("confirm", skin);
		confirmButton.addListener(new ChangeListener() {
			
			@Override
			public void changed(ChangeEvent event, Actor actor) {
				confirmed = true;
				selectedMusic = Gdx.files.absolute(path+System.getProperty("file.separator")+musicList.getSelected());
				miniSender.send(MiniEvents.MUSIC_SELECTED);
			}
		});
		add(confirmButton);
		TextButton regenMap = new TextButton("regen map", skin);
		regenMap.addListener(new ChangeListener() {
			
			@Override
			public void changed(ChangeEvent event, Actor actor) {
				miniSender.send(MiniEvents.MUSIC_DATA_CLEANED);
			}
		});
		add(regenMap);
		
		row();
		
		listScroller = new ScrollPane(musicList, skin);
		listScroller.setScrollingDisabled(true, false);
		
		add(listScroller).colspan(2).expand().fill().prefWidth(getWidth()-5);

	}
	
	public void refresh() {
		fileNames.clear();
		FileHandle[] musicListArray = Gdx.files.absolute(path).list();
		for (int i = 0; i < musicListArray.length; i++) {
			if (musicListArray[i].name().toLowerCase().endsWith(".wav") || musicListArray[i].name().toLowerCase().endsWith(".mp3")) {
				fileNames.add(musicListArray[i].name());
			}
		}
		fileNames.sort();
		musicList.setItems(fileNames);
		
	}
	
	public boolean isConfirmed() {
		boolean isConfirmed = confirmed;
		confirmed = false;
		return isConfirmed;
	}
	
	public boolean isBack() {
		boolean isBack = back;
		back = false;
		return isBack;
	}
	
	public AudioData getSelectedMusic() {
		if (selectedMusic != null) {
			return Audio.getAudioData(selectedMusic);
		} else {
			return null;
		}
	}
}
