package theGhastModding.midiToolbox.main;

import java.awt.Dimension;

import javax.swing.JPanel;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;

import com.leff.midi.MidiFile;
import com.leff.midi.MidiTrack;
import com.leff.midi.event.MidiEvent;
import com.leff.midi.event.ProgramChange;
import com.leff.midi.event.meta.Tempo;
import com.leff.midi.event.meta.TimeSignature;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.awt.event.ActionEvent;

@SuppressWarnings("serial")
public class TrackSplitterPanel extends JPanel {
	
	public TrackSplitterPanel(){
		super();
		setPreferredSize(new Dimension(700, 300));
		
		setFocusable(true);
		setLayout(null);
		
		JButton btnNewButton = new JButton("Split them tracks");
		JFileChooser midiChooser = new JFileChooser();
		midiChooser.setDialogTitle("Select MIDI");
        FileFilter filter3 = new FileNameExtensionFilter("MIDI files", 
                "mid", "midi", "MID", "MIDI");  
        midiChooser.setFileFilter(filter3);
		btnNewButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				int option = midiChooser.showOpenDialog(TGMMIDIToolbox.frame);
				if(option == JFileChooser.APPROVE_OPTION){
					File selectedMidi = midiChooser.getSelectedFile();
					if(!selectedMidi.exists()){
		        		JOptionPane.showMessageDialog(null, "The selected MIDI doesnt exist", "Error", JOptionPane.ERROR_MESSAGE);
		        		return;
					}
					try {
						MidiFile midi = new MidiFile(selectedMidi);
						ArrayList<MidiEvent> importantEvents = new ArrayList<MidiEvent>();
						for(int i = 0; i < midi.getTracks().size(); i++){
							MidiTrack track = midi.getTracks().get(i);
							Iterator<MidiEvent> it = track.getEvents().iterator();
							while(it.hasNext())
							{
								MidiEvent event = it.next();
								if(event instanceof Tempo){
									importantEvents.add(event);
								}
								if(event instanceof ProgramChange){
									importantEvents.add(event);
								}
								if(event instanceof TimeSignature){
									importantEvents.add(event);
								}
							}
						}
						for(int i = 0; i < midi.getTracks().size(); i++){
							MidiTrack track = midi.getTracks().get(i);
							track.insertAll(importantEvents);
							MidiFile outputMidi = new MidiFile(midi.getResolution());
							outputMidi.addTrack(track);
							outputMidi.setType(0);
							outputMidi.writeToFile(new File(i + ".mid"));
						}
					} catch(Exception e2){
		        		JOptionPane.showMessageDialog(null, "Error splitting tracks", "Error", JOptionPane.ERROR_MESSAGE);
		        		e2.printStackTrace();
		        		return;
					}
				}
			}
		});
		btnNewButton.setBounds(10, 116, 659, 23);
		add(btnNewButton);
		requestFocus();
	}
}
