package zero1hd.rhythmbullet.ui.components;

import com.badlogic.gdx.Preferences;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.ui.Widget;
import com.badlogic.gdx.utils.Disposable;

import zero1hd.rhythmbullet.audio.SongInfo;

public class MusicSelectable extends Widget implements Disposable {
	private Table table;

	private Image imageIcon;
	private ScrollText displayName;
	private Label durationLabel;
	private Label authorLabel;

	private FileHandle musicFile;

	private Texture albumCover;
	private SongInfo songInfo;
	
	private boolean selected;
	
	public MusicSelectable(FileHandle musicFile, Preferences musicAnnotation, Skin skin, Texture defaultAlbumC) {
		table = new Table(skin);
		table.setBackground("holo-pane");
		table.setFillParent(true);

		setName(musicFile.name());

		this.albumCover = defaultAlbumC;
		this.musicFile = musicFile;
		songInfo = new SongInfo(musicFile, musicAnnotation);

		imageIcon = new Image(albumCover);
		table.add(imageIcon);

		displayName = new ScrollText(musicFile.name(), skin, true);
		table.add(displayName);

		table.row();

		durationLabel = new Label("Loading...", skin, "sub-font");
		table.add(durationLabel);

		authorLabel = new Label("Loading...", skin, "sub-font");

		table.defaults().pad(10f);
	}

	public void updateInfo() {
		durationLabel.setText("Runtime: "
				+ ((songInfo.getDurationInSeconds() / 60 < 1) ? "00" : songInfo.getDurationInSeconds() / 60) + ":"
				+ ((songInfo.getDurationInSeconds() - (songInfo.getDurationInSeconds() / 60) * 60) < 10
						? "0" + (songInfo.getDurationInSeconds() - (songInfo.getDurationInSeconds() / 60) * 60)
						: (songInfo.getDurationInSeconds() - (songInfo.getDurationInSeconds() / 60) * 60)));
		authorLabel.setText("Author: " + songInfo.getAuthor());
	}

	public FileHandle getMusicFile() {
		return musicFile;
	}

	public SongInfo getAudioInfo() {
		return songInfo;
	}

	@Override
	public void dispose() {
		songInfo.dispose();
	}

	public boolean isMusicInvalid() {
		return songInfo.isInvalidMusic();
	}
	
	public void select() {
		table.setBackground("holo-pane-down");
		selected = true;
	}
	
	public void diselect() {
		table.setBackground("holo-pane");
		selected = false;
	}
	
	public boolean isSelected() {
		return selected;
	}
}
