import javax.sound.midi.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;

public class test5lun extends JPanel implements Runnable
{
	Synthesizer	synth = null;
	MidiChannel[] channels;
	int timeLine = 0;
	ArrayList pallette;
	Thread thread;
	public test5lun()
	{
		// Ricerca del sintetizzatore midi di default
		try { synth = MidiSystem.getSynthesizer(); } catch (MidiUnavailableException e){}
		// apertura del sintetizzatore selezionato
		try{ synth.open();} catch (MidiUnavailableException e) {e.printStackTrace();System.exit(1);}
		channels = synth.getChannels();
		pallette = new ArrayList();
		addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e){
			pallette.add(new Palla(e.getX(), e.getY(), 6));
			}});
		thread = new Thread(this);
		thread.start();
	}
	public void suonaNota(int nota, int canale)
	{
		int nNoteNumber = Math.min(127, Math.max(0, nota));
		int nVelocity = Math.min(127, Math.max(0, 100));
		channels[canale].noteOn(nNoteNumber, nVelocity);
	}
	
	public void run()
	{
		while(thread != null)
		{
			timeLine++;
			if (timeLine >= 400) timeLine = 0;
			repaint();
			try {thread.sleep(10); } catch(Exception ee){}
		}
	}
	
	public void paint(Graphics g)
	{
		super.paintComponent(g);
		g.setColor(Color.black);
		g.drawLine(timeLine, 0, timeLine, 400);
		for (int k = 0; k < pallette.size(); k++)
		{
			Palla pallaCorrente = (Palla)pallette.get(k);
			pallaCorrente.mostra(g);
			if (timeLine == pallaCorrente.x)
			{
				pallaCorrente.selected = !pallaCorrente.selected;
				suonaNota(getHeight() - pallaCorrente.y, 1);
			}
		}
	}
	
	public static void main(String[] a)
	{
		JFrame f = new JFrame();
		f.setTitle("Test 5 - Luned́");
		f.setSize(400,127);
		f.add(new test5lun());
		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		f.setVisible(true);
	}
}

class Palla
{
	int x, y, dim;
	boolean selected = false;
	public Palla(int x, int y, int dim)
	{
		this.x = x;
		this.y = y;
		this.dim = dim;
	}
	public void mostra(Graphics g)
	{
		if (selected)
			g.setColor(Color.red);
		else
			g.setColor(Color.blue);
		g.fillOval(x-dim/2, y-dim/2, dim, dim);
	}
	public boolean dentro(int cx, int cy)
	{
		if (cx > x-dim/2 && cx < x+dim/2 && cy > y-dim/2 && cy < y+dim/2)
			return true;
		else
			return false;
	}
}
