package theGhastModding.midiToolbox.main;

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
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.NoteOff;
import com.leff.midi.event.NoteOn;
import com.leff.midi.event.meta.Tempo;
import com.leff.midi.event.meta.TimeSignature;

@SuppressWarnings("serial")
public class BinaryMessageCreatorPanel extends JPanel {
	
	private JTextField textField;
	
	public BinaryMessageCreatorPanel(){
		setLayout(null);
		setPreferredSize(new Dimension(700, 300));
		
		textField = new JTextField();
		textField.setHorizontalAlignment(SwingConstants.CENTER);
		textField.setBounds(20, 39, 658, 20);
		add(textField);
		textField.setColumns(10);
		
		JLabel lblThisToolConverts = new JLabel("This tool converts a string of text to a row of short and long notes that encode the text in binary");
		lblThisToolConverts.setHorizontalAlignment(SwingConstants.CENTER);
		lblThisToolConverts.setBounds(10, 11, 668, 14);
		add(lblThisToolConverts);
		
		JFileChooser midiSaveChooser = new JFileChooser();
        FileFilter filter3 = new FileNameExtensionFilter("MIDI files", 
                "mid");  
        midiSaveChooser.setFileFilter(filter3);
        midiSaveChooser.setDialogTitle("Choose where to save MIDI");
		
		JCheckBox chckbxPutSpacesBetween = new JCheckBox("Put spaces between every byte (8 bits)");
		chckbxPutSpacesBetween.setSelected(true);
		chckbxPutSpacesBetween.setBounds(20, 99, 658, 23);
		add(chckbxPutSpacesBetween);
        
		JButton btnCreateMidi = new JButton("Create MIDI");
		btnCreateMidi.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if(textField.getText() == null || textField.getText().isEmpty() || textField.getText() == ""){
					JOptionPane.showMessageDialog(TGMMIDIToolbox.frame, "Please enter a message", "Error", JOptionPane.ERROR_MESSAGE);
					return;
				}
				MidiFile midi = new MidiFile(MidiFile.DEFAULT_RESOLUTION);
				Tempo tempo = new Tempo();
				TimeSignature signature = new TimeSignature();
				MidiTrack track = new MidiTrack();
				track.insertEvent(tempo);
				track.insertEvent(signature);
				midi.addTrack(track);
				MidiTrack noteTrack = new MidiTrack();
				  byte[] bytes = textField.getText().getBytes();
				  StringBuilder binary = new StringBuilder();
				  for (byte b : bytes)
				  {
				     int val = b;
				     for (int i = 0; i < 8; i++)
				     {
				        binary.append((val & 128) == 0 ? 0 : 1);
				        val <<= 1;
				     }
				     binary.append(' ');
				  }
				  String binaryString = binary.toString();
				  long position = 0;
				  for(char c:binaryString.toCharArray()){
					  if(c == ' '){
						  if(chckbxPutSpacesBetween.isSelected()){
							  position += 30;
						  }
						  continue;
					  }
					  if(c == '0'){
						  NoteOn on = new NoteOn(position,0,54,100);
						  NoteOff off = new NoteOff(position + 10,0,54,100);
						  position += 10;
						  noteTrack.insertEvent(on);
						  noteTrack.insertEvent(off);
					  }
					  if(c == '1'){
						  NoteOn on = new NoteOn(position,0,54,100);
						  NoteOff off = new NoteOff(position + 20,0,54,100);
						  position += 20;
						  noteTrack.insertEvent(on);
						  noteTrack.insertEvent(off);
					  }
				  }
				midi.addTrack(noteTrack);
				int option2 = midiSaveChooser.showSaveDialog(TGMMIDIToolbox.frame);
				File f = midiSaveChooser.getSelectedFile();
				if(!(f.getName().toUpperCase().endsWith(".MID") || f.getName().toUpperCase().endsWith(".MIDI"))) {
					f = new File(f.getPath() + ".mid");
				}
				if(option2 == JFileChooser.APPROVE_OPTION){
					if(f.exists()){
						int option3 = JOptionPane.showConfirmDialog(TGMMIDIToolbox.frame, "The selected file allready exists. Do you want to overwrite the file?", "Question",JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
						if(option3 == 1){
							return;
						}
					}
					try {
						midi.writeToFile(f);
					} catch(Exception e3){
						JOptionPane.showMessageDialog(TGMMIDIToolbox.frame, "Error saving MIDI", "Error", JOptionPane.ERROR_MESSAGE);
						e3.printStackTrace();
						return;
					}
					JOptionPane.showMessageDialog(TGMMIDIToolbox.frame, "Successfully generated message in MIDI", "Message", JOptionPane.INFORMATION_MESSAGE);
				}
			}
		});
		btnCreateMidi.setBounds(20, 70, 658, 23);
		add(btnCreateMidi);
		
	}
}
