package rpgEngine.Data.Raw.Sound;

import java.io.InputStream;

import javax.sound.midi.MidiSystem;
import javax.sound.midi.Sequencer;



public class MidiSound extends GenericSound {
	private String filename;
	private String name;
    private Sequencer seq;
	
	public MidiSound() {
		this("","");
	}
	
	public MidiSound(String n, String f) {
		name = n;
		filename = f;
	}
	
	
	@Override
	public void play() {
        if(seq == null) {
            openFile();
        }
        
        if(seq != null) {
            seq.start();
        }
	}

	@Override
	public void stop() {
		if(seq != null) {
            seq.stop();
            seq.close();
            seq = null;
        }
	}

	
    private void openFile() {
    	InputStream stream = null;
    	
        try {
            seq = MidiSystem.getSequencer();
            
            //stream = this.getClass().getResource("../../Resources/Audio/" + filename).openStream();
            stream = this.getClass().getClassLoader().getResourceAsStream("rpgEngine/Resources/Audio/" + filename);
            
            seq.setSequence(MidiSystem.getSequence(stream));
            seq.setLoopCount(-1);
            seq.open();
        }
        catch(Exception e) {
            System.err.println(e.toString());
            seq = null;
        }
    }

    
	@Override
	public String getName() {
		return name;
	}
	
	
	@Override
	public String getFilename() {
		return filename;
	}

}
