package theGhastModding.midiEditor.midi;

import java.io.File;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.util.List;

import javax.swing.JOptionPane;

import theGhastModding.midiEditor.main.MIDIEditorStart;

public class MIDISaver {
	
	public MIDISaver(File f, List<Track> tracks, int TPB) throws Exception {
		saveMidi(new FileOutputStream(f), tracks, TPB);
	}
	
	public MIDISaver(FileOutputStream fos, List<Track> tracks, int TPB) throws Exception {
		saveMidi(fos, tracks, TPB);
	}
	
	private void saveMidi(FileOutputStream fos, List<Track> tracks, int TPB) throws Exception {
		fos.write("MThd".getBytes());
		fos.write(new byte[]{0,0,0,6});
		fos.write(shortToBytes((short)1));
		int trackCount = tracks.size();
		if(trackCount > 6000){
			JOptionPane.showMessageDialog(MIDIEditorStart.frame, "MIDI contains more then 6000 tracks. Track limit is 6000 tracks, as such only the first 6000 tracks will be saved.", "Error", JOptionPane.WARNING_MESSAGE);
			trackCount = 6000;
		}
		fos.write(shortToBytes((short)trackCount));
		fos.write(shortToBytes((short)TPB));
		fos.flush();
		for(int i = 0; i < trackCount; i++){
			System.out.println("Saving track " + Integer.toString(i + 1) + " from " + Integer.toString(trackCount));
			boolean b = tracks.get(i).saveTrack(fos);
			if(!b){
				fos.close();
				return;
			}
		}
		fos.flush();
		fos.close();
		System.out.println("Done saving");
	}
	
	public void cleanUp(){
		//TODO: implement dat shiat
	}
	
	private ByteBuffer buffer;
	
	/*public int bytesToInt(byte[] bytes) {
	    buffer = ByteBuffer.allocate(Integer.BYTES);
	    buffer.put(bytes);
	    buffer.flip();
	    return buffer.getInt();
	}*/
	
	public byte[] intToBytes(int x) {
	    buffer = ByteBuffer.allocate(Integer.BYTES/*Thats 4 bytes*/);
	    buffer.putInt(x);
	    return buffer.array();
	}
	
	public byte[] shortToBytes(short x){
		buffer = ByteBuffer.allocate(Short.BYTES);
		buffer.putShort(x);
		return buffer.array();
	}
	
}