package zero1hd.rhythmbullet.audio.metadata;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.jaudiotagger.audio.AudioFile;
import org.jaudiotagger.audio.AudioFileIO;
import org.jaudiotagger.audio.exceptions.CannotReadException;
import org.jaudiotagger.audio.exceptions.InvalidAudioFrameException;
import org.jaudiotagger.audio.exceptions.ReadOnlyFileException;
import org.jaudiotagger.tag.FieldKey;
import org.jaudiotagger.tag.Tag;
import org.jaudiotagger.tag.TagException;
import org.jaudiotagger.tag.images.Artwork;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.Texture;

public class WAVMetadata implements AudioMetadata {
	private String title, author, duration, genre;
	private int length;
	private Texture albumCover;
	private FileHandle fileHandle;
	private Pixmap pixmap;
	
	public WAVMetadata(FileHandle fileHandle) {
		this.fileHandle = fileHandle;
		
		try {
			AudioFile wav = AudioFileIO.read(fileHandle.file());
			length = wav.getAudioHeader().getTrackLength();
			SimpleDateFormat f = new SimpleDateFormat("m:ss");
			duration = f.format(new Date(length*1000));
			
			Tag tag = wav.getTag();
			title = tag.getFirst(FieldKey.TITLE);
			author = tag.getFirst(FieldKey.ARTIST);
			genre = tag.getFirst(FieldKey.GENRE);
			if (title.isEmpty()) {
				title = fileHandle.nameWithoutExtension().replace('_', ' ');
			}
		} catch (CannotReadException | IOException | TagException | ReadOnlyFileException | InvalidAudioFrameException e) {
			Gdx.app.error("WAVMetadata", "Failed to read metadata of file: " + fileHandle.name());
		}
	}
	
	@Override
	public void loadAlbumCover() {
		if (pixmap == null) {
			try {
				AudioFile wav = AudioFileIO.read(fileHandle.file());
				Artwork art = wav.getTag().getFirstArtwork();
				
				if (art != null) {
					byte[] imageData = art.getBinaryData();
					pixmap = new Pixmap(imageData, 0, imageData.length);
				}
			} catch (CannotReadException | IOException | TagException | ReadOnlyFileException | InvalidAudioFrameException e) {
				e.printStackTrace();
			}
		}
	}
	@Override
	public void unloadAlbumCover() {
		if (albumCover != null) {
			albumCover.dispose();
			albumCover = null;
		}
	}
	@Override
	public String getAuthor() {
		return author;
	}
	@Override
	public String getTitle() {
		return title;
	}
	@Override
	public String getDuration() {
		return duration;
	}
	
	@Override
	public int getLength() {
		return length;
	}
	
	@Override
	public Texture getAlbumCover() {
		if (pixmap != null && albumCover == null) {
			albumCover = new Texture(pixmap);
			pixmap.dispose();
			pixmap = null;
		}
		return albumCover;
	}
	@Override
	public String getGenre() {
		return genre;
	}
	@Override
	public FileHandle getFileHandle() {
		return fileHandle;
	}
	@Override
	public void dispose() {
		unloadAlbumCover();
	}
	

}
