package zero1hd.rhythmbullet.ui.pages;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Preferences;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.ui.ScrollPane;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener;
import com.badlogic.gdx.utils.Array;

import zero1hd.rhythmbullet.audio.SongInfo;
import zero1hd.rhythmbullet.audio.SongList;
import zero1hd.rhythmbullet.ui.components.MusicSelectable;
import zero1hd.rhythmbullet.util.MiniEvents;

public class MusicSelectionPage extends Page {
	Preferences musicFileAnnotation;
	
	private SongList songList;
	private Array<MusicSelectable> selectables;
	private Table songTable;
	private ScrollPane scrollbar;
	private TextButton back;
	
	private FileHandle selectedMusic;
	private SongInfo selectedMusicInfo;
	
	private Skin skin;
	private AssetManager assets;
	public MusicSelectionPage(Skin skin, SongList songList, AssetManager assetManager) {
		super("Select music", skin);
		this.songList = songList;
		musicFileAnnotation = Gdx.app.getPreferences("music_file_annotation");
		this.assets = assetManager;
		songTable = new Table(skin);
		scrollbar = new ScrollPane(songTable, skin);
		scrollbar.setSize(0.4f*getWidth(), getHeightBelowTitle());
		addActor(scrollbar);
		selectables = new Array<>();
		this.skin = skin;
		back = new TextButton("Back", skin);
		back.setPosition(getWidth()-back.getWidth()-15f, getHeightBelowTitle());
		back.addListener(new ChangeListener() {
			@Override
			public void changed(ChangeEvent event, Actor actor) {
				miniSender.send(MiniEvents.BACK);
			}
		});
		addActor(back);
		
		back.toFront();
	}
	
	@Override
	public void act(float delta) {
		super.act(delta);
	}
	
	public FileHandle getSelectedMusic() {
		return selectedMusic;
	}
	
	public SongInfo getSelectedMusicInfo() {
		return selectedMusicInfo;
	}
	
	public void refresh() {
		for (int i = 0; i < songList.getAmountOfSongs(); i++) {
			MusicSelectable selectable = new MusicSelectable(songList.getSongFileHandleFromIndex(i), musicFileAnnotation, skin, assets.get("defaultCover.png", Texture.class));
			selectables.add(selectable);
			songTable.add(selectable);
			songTable.row();
		}
		
		ExecutorService exec = Executors.newSingleThreadExecutor();
		exec.submit(() -> {
			for (int i = 0; i < selectables.size; i++) {
				MusicSelectable info = selectables.get(i);
				info.getAudioInfo().loadInfo();
				info.getAudioInfo().doesContainsInformation();
				Gdx.app.postRunnable(() -> {
					info.updateInfo();
				});
			}
		});
	}
}
