package kr.gui.util;

import java.awt.Component;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.JPopupMenu;

import kr.gui.metrodome.MetrodomeGraph;
import kr.gui.metrodome.MetrodomeGuiModel;
import kr.gui.midigraph.MidiGraph;
import kr.miditunemodel.Event;
import kr.miditunemodel.EventGroup;
import kr.miditunemodel.EventGuiModel;
import kr.miditunemodel.KREvent;
import kr.miditunemodel.MetrodomeEvent;
import kr.miditunemodel.MidiTuneModel;

/**
 * Handles default behavior such as selecting events with shift and control click, and deleting events with the delete key
 */
public abstract class DefaultUIMode<EVENT extends Event> implements UIMode, MouseListener, KeyListener
{
	private MidiGraph<EVENT> comp;
	private EventGuiModel<EVENT> eventGuiModel;
	private MidiTuneModel midiTuneModel;
	private EventGroup<EVENT> eg;
	
	public DefaultUIMode(EventGuiModel<EVENT> eventGuiModel, MidiGraph comp, MidiTuneModel midiTuneModel,
			EventGroup<EVENT> eg)
	{
		this.midiTuneModel = midiTuneModel;
		this.eventGuiModel = eventGuiModel;
		this.comp = comp;
		this.eg = eg;
	}

	public void start(Component comp) {
		comp.addMouseListener(this);
		comp.addKeyListener(this);
	}

	public void stop(Component comp) {
		comp.removeMouseListener(this);
		comp.removeKeyListener(this);		
	}
	
	public void mousePressed(MouseEvent e)
	{
		mousePressed(e,comp.getEvent(e.getX(), e.getY()));
	}

	protected void mousePressed(MouseEvent e, EVENT event) 
	{
		if(e.getButton() == MouseEvent.BUTTON1)
		{
			if(e.isShiftDown())
			{
				if(event != null && eventGuiModel.getActiveEvent() != null)
				{
					//select a bunch of notes
					eventGuiModel.addSelectedEvents(
							eg.getEventsBetween(event, eventGuiModel.getActiveEvent()));
				}
			}
			else if(e.isControlDown())
			{
				//select another note
				if(event != null)
				{
					eventGuiModel.addSelectedEvent(event);
					eventGuiModel.setActiveEvent(event);
				}
			}
			else
			{
				//nothing selected
				eventGuiModel.clearSelectedEvents();
				eventGuiModel.addSelectedEvent(event);
				eventGuiModel.setActiveEvent(event);
			}				
		}
	}

	public void mouseClicked(MouseEvent e) {
	}

	public void mouseReleased(MouseEvent e) {
	}

	public void mouseEntered(MouseEvent e) {
	}

	public void mouseExited(MouseEvent e) {
	}

	public void keyTyped(KeyEvent e) {
	}

	public void keyPressed(KeyEvent e) {
		if(e.getKeyCode() == e.VK_DELETE)
		{
			boolean containsLastComponent = false;
			for(EVENT ne : eventGuiModel.getSelectedEvents())
			{
				if(ne.isTail())
					containsLastComponent = true;
				eg.removeEvent(ne);
			}
			
			eventGuiModel.clearSelectedEvents();
			
			eg.notifyChanged(true);
			
			e.consume();
		}
	}

	public void keyReleased(KeyEvent e) {
	}

}
