package zero1hd.rhythmbullet.audio;

import java.io.IOException;

import org.jaudiotagger.audio.AudioFile;
import org.jaudiotagger.audio.AudioFileIO;
import org.jaudiotagger.audio.AudioHeader;
import org.jaudiotagger.audio.exceptions.CannotReadException;
import org.jaudiotagger.audio.exceptions.InvalidAudioFrameException;
import org.jaudiotagger.audio.exceptions.ReadOnlyFileException;
import org.jaudiotagger.audio.mp3.MP3AudioHeader;
import org.jaudiotagger.audio.mp3.MP3File;
import org.jaudiotagger.tag.TagException;

import com.badlogic.gdx.files.FileHandle;

public class MinimalAudioHeader {
	private int sampleRate, channelCount;
	private SupportedFormats format;
	private FileHandle musicFile;
	public MinimalAudioHeader(FileHandle musicFile) {
		if (musicFile == null) throw new IllegalArgumentException("musicFile for minimal audio headers should not be null.");
		this.musicFile = musicFile;
		format = SupportedFormats.valueOf(musicFile.extension().toUpperCase());
		try {
			AudioFile file = AudioFileIO.read(musicFile.file());
			AudioHeader header = file.getAudioHeader();
			sampleRate = header.getSampleRateAsNumber();
			channelCount = (header.getChannels().equals("Mono") ? 1 : 2);
		} catch (CannotReadException | IOException | TagException | ReadOnlyFileException | InvalidAudioFrameException e) {
			e.printStackTrace();
		}
	}
	
	
	
	public int getSampleRate() {
		return sampleRate;
	}
	
	public int getChannelCount() {
		return channelCount;
	}
	
	
	public long estimateSampleFrames() {
		switch (format) {
		case MP3:
			try {
				MP3File file = (MP3File) AudioFileIO.read(musicFile.file());
				MP3AudioHeader header = file.getMP3AudioHeader();
				return header.getNumberOfFrames();
			} catch (CannotReadException | IOException | TagException | ReadOnlyFileException | InvalidAudioFrameException e) {
				e.printStackTrace();
			}
			return -1;
		default:
			return -1;
		}
	}
}
