package theGhastModding.midiToolbox.main;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
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.NoteOff;
import com.leff.midi.event.NoteOn;
import com.leff.midi.event.meta.Tempo;
import com.leff.midi.event.meta.TimeSignature;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;

@SuppressWarnings("serial")
public class ImageToNoteartPanel extends JPanel {
	
	private String selectedImage = null;
	
	public ImageToNoteartPanel(){
		setLayout(null);
		setPreferredSize(new Dimension(700, 300));
		JFileChooser imageChooser = new JFileChooser();
        FileFilter filter2 = new FileNameExtensionFilter("Image files", 
                "png", "jpg");  
        imageChooser.setFileFilter(filter2);
        imageChooser.setDialogTitle("Choose image");
		JFileChooser midiSaveChooser = new JFileChooser();
        FileFilter filter3 = new FileNameExtensionFilter("MIDI files", 
                "mid");  
        midiSaveChooser.setFileFilter(filter3);
        midiSaveChooser.setDialogTitle("Choose where to save MIDI");
        
		JLabel lblSelectedImage = new JLabel("Selected Image:");
		lblSelectedImage.setBounds(10, 140, 678, 16);
		add(lblSelectedImage);
        
		JButton btnSelectImage = new JButton("Select Image");
		btnSelectImage.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				int option = imageChooser.showOpenDialog(TGMMIDIToolbox.frame);
				if(option == JFileChooser.APPROVE_OPTION){
					if(imageChooser.getSelectedFile().exists()){
						selectedImage = imageChooser.getSelectedFile().getPath();
						lblSelectedImage.setText("Selected Image: " + imageChooser.getSelectedFile().getName());
					}else{
						JOptionPane.showMessageDialog(TGMMIDIToolbox.frame, "The selected file doesnt exist", "Error", JOptionPane.ERROR_MESSAGE);
						return;
					}
				}
			}
		});
		btnSelectImage.setBounds(10, 106, 430, 23);
		add(btnSelectImage);
		
		JLabel lblThisToolConverts = new JLabel("This tool converts image to noteart");
		lblThisToolConverts.setBounds(10, 11, 430, 16);
		add(lblThisToolConverts);
		
		JLabel lblImagesCanNot = new JLabel("Images can not be wider then 128 pixels");
		lblImagesCanNot.setBounds(10, 33, 430, 16);
		add(lblImagesCanNot);
		
		JLabel lblOnlyPixelsWith = new JLabel("Only pixels with the RGB colour of 0,0,0 will be converted to notes");
		lblOnlyPixelsWith.setBounds(10, 60, 430, 16);
		add(lblOnlyPixelsWith);
		
		JLabel lblVelocityOfNoteart = new JLabel("Velocity:");
		lblVelocityOfNoteart.setBounds(10, 225, 114, 16);
		add(lblVelocityOfNoteart);
		
		JSpinner spinner = new JSpinner();
		spinner.setModel(new SpinnerNumberModel(1, 1, 100, 1));
		spinner.setBounds(133, 223, 42, 20);
		add(spinner);
		
		JLabel lblResolution = new JLabel("Resolution:");
		lblResolution.setBounds(193, 225, 114, 16);
		add(lblResolution);
		
		JSpinner spinner_1 = new JSpinner();
		spinner_1.setModel(new SpinnerNumberModel(new Integer(10), new Integer(1), null, new Integer(1)));
		spinner_1.setBounds(325, 223, 42, 20);
		add(spinner_1);
		
		JButton btnConvertToMidi = new JButton("Convert to MIDI");
		btnConvertToMidi.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if(selectedImage.isEmpty() || selectedImage == "" || selectedImage == null){
					JOptionPane.showMessageDialog(TGMMIDIToolbox.frame, "No image has been selected", "Error", JOptionPane.ERROR_MESSAGE);
					return;
				}
				File image = new File(selectedImage);
				if(!image.exists()){
					JOptionPane.showMessageDialog(TGMMIDIToolbox.frame, "The selected image doesnt exist", "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();
				BufferedImage currentImage = null;
				try {
					currentImage = ImageIO.read(image);
				} catch(Exception e2){
					JOptionPane.showMessageDialog(TGMMIDIToolbox.frame, "Error loading image", "Error", JOptionPane.ERROR_MESSAGE);
					e2.printStackTrace();
					return;
				}
				if(currentImage == null){
					JOptionPane.showMessageDialog(TGMMIDIToolbox.frame, "Error loading image", "Error", JOptionPane.ERROR_MESSAGE);
					return;
				}
				int resolution = Integer.parseInt(spinner_1.getValue().toString());
				for(int i = 0; i < currentImage.getWidth(); i++){
					for(int j = 0; j < currentImage.getHeight(); j++){
						Color color = new Color(currentImage.getRGB(i, j));
						if(color.getRed() != 255 && color.getBlue() != 255 && color.getGreen() != 255){
							if(i >= 128 || i < 0){
								continue;
							}
							NoteOn on = new NoteOn(currentImage.getHeight() * resolution - j * resolution,5, i,Integer.parseInt(spinner.getValue().toString()));
							noteTrack.insertEvent(on);
							NoteOff off = new NoteOff(currentImage.getHeight() * resolution - j * resolution + resolution - 1,5,i,0);
							noteTrack.insertEvent(off);
						}
					}
				}
				midi.addTrack(noteTrack);
				int option2 = midiSaveChooser.showSaveDialog(TGMMIDIToolbox.frame);
				if(option2 == JFileChooser.APPROVE_OPTION){
					if(midiSaveChooser.getSelectedFile().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(midiSaveChooser.getSelectedFile());
					} catch(Exception e3){
						JOptionPane.showMessageDialog(TGMMIDIToolbox.frame, "Error saving MIDI", "Error", JOptionPane.ERROR_MESSAGE);
						e3.printStackTrace();
						return;
					}
					JOptionPane.showMessageDialog(TGMMIDIToolbox.frame, "Successfully generated noteart", "Message", JOptionPane.INFORMATION_MESSAGE);
				}
			}
		});
		btnConvertToMidi.setBounds(10, 171, 430, 26);
		add(btnConvertToMidi);
		
		JLabel lblSettings = new JLabel("Settings:");
		lblSettings.setBounds(10, 202, 55, 16);
		add(lblSettings);
		
	}
}
