package theGhastModding.tgmidi.midi;

import javax.sound.midi.MidiMessage;
import javax.sound.midi.Receiver;
import javax.swing.JOptionPane;

import theGhastModding.synthesizer.main.MidiEvent;
import theGhastModding.synthesizer.main.TGMSynthesizer;
import theGhastModding.tgmidi.main.TGMIDIMain;

public class LoopMidiReceiver implements Receiver {
	
	public LoopMidiReceiver(){
		
	}
	
	@Override
	public void close() {
		
	}
	
	@Override
	public void send(MidiMessage message, long timeStamp) {
		try {
			if(message.getStatus() >= 0x80 || message.getStatus() <= 0x8F){
				if(message.getMessage().length < 3){
					return;
				}
				TGMSynthesizer.sendEvent(new MidiEvent(MidiEvent.MIDI_EVENT_NOTE, message.getStatus() - 0x80, message.getMessage()[1] & 0xff, 0));
			}
			if(message.getStatus() >= 0x90 || message.getStatus() <= 0x9F){
				if(message.getMessage().length < 3){
					return;
				}
				TGMSynthesizer.sendEvent(new MidiEvent(MidiEvent.MIDI_EVENT_NOTE, message.getStatus() - 0x90, message.getMessage()[1] & 0xff, message.getMessage()[2] & 0xff));
			}
			if(message.getStatus() >= 0xC0 || message.getStatus() <= 0xCF){
				TGMSynthesizer.sendEvent(new MidiEvent(MidiEvent.MIDI_EVENT_PROGRAM, message.getStatus() - 0xC0, message.getMessage()[1] & 0xff, 0));
			}
			if(message.getStatus() >= 0xB0 || message.getStatus() <= 0xBF){
				if(message.getMessage().length < 3){
					return;
				}
				TGMSynthesizer.sendEvent(new MidiEvent(MidiEvent.MIDI_EVENT_CONTROL, message.getStatus() - 0xB0, message.getMessage()[1] & 0xff, message.getMessage()[2] & 0xff));
			}
			if(message.getStatus() >= 0xD0 || message.getStatus() <= 0xDF){
				TGMSynthesizer.sendEvent(new MidiEvent(MidiEvent.MIDI_EVENT_CHANPRES, message.getStatus() - 0xB0, message.getMessage()[1] & 0xff, 0));
			}
			if(message.getStatus() >= 0xE0 || message.getStatus() <= 0xEF){
				if(message.getMessage().length < 3){
					return;
				}
				TGMSynthesizer.sendEvent(new MidiEvent(MidiEvent.MIDI_EVENT_PITCH, message.getStatus() - 0xB0, message.getMessage()[1] & 0xff, message.getMessage()[2] & 0xff));
			}
		} catch(Exception e){
			e.printStackTrace();
			JOptionPane.showMessageDialog(TGMIDIMain.frame, "Error parsing MIDI event from loopMIDI", "Error", JOptionPane.ERROR_MESSAGE);
			return;
		}
	}
	
}