package kr.gui.midigraph;

import java.awt.Color;
import java.awt.Graphics2D;

import kr.TimeKeeper;
import kr.gui.GuiModel;
import kr.gui.XScrollingPane;
import kr.miditunemodel.Event;

public abstract class MidiGraph<T extends Event> extends XScrollingPane
{
	protected GuiModel guiModel;
	private TimeKeeper timeKeeper;

	public MidiGraph(GuiModel guiModel) {
		this(guiModel, guiModel);
	}
	
	public MidiGraph(GuiModel guiModel, TimeKeeper timeKeeper) {
		this.guiModel = guiModel;
		this.timeKeeper = timeKeeper;
	}

	protected void doOverlapPaint(Graphics2D g) {
		// draw line representing now
		int nowX = guiModel.calcNowX(getWidth());
		g.setColor(Color.GRAY);
		g.drawLine(nowX, 0, nowX, getHeight());

	}

	@Override
	protected int getScrollAbs() {
		return guiModel.microsToAbsPixels(timeKeeper.getCurrMicros());
	}

	public int microsToPixels(long micros)
	{
		return microsToPixels(getWidth(), timeKeeper.getCurrMicros(), micros);
	}
	
	public int microsToRelPixels(long micros)
	{
		return (int)Math.round(guiModel.getZoomLevel() * micros);
	}

	int microsToPixels(int w, long nowMicros, long micros) 
	{
		int nowX = guiModel.calcNowX(w);
		
		return (int)Math.round(guiModel.getZoomLevel() * (micros - nowMicros) + nowX); 
	}

	long pixelsToMicros(int w, long nowMicros, int xPos) 
	{
		int nowX = guiModel.calcNowX(w);
		
		return Math.round((xPos - nowX) / guiModel.getZoomLevel() + nowMicros); 
	}

	public long pixelsToMicros(int x) {
		return pixelsToMicros(getWidth(), timeKeeper.getCurrMicros(), x);
	}


	public long pixelsToRelMicros(int pixels) {
		return Math.round(pixels / guiModel.getZoomLevel());
	}
	
	public long getStartMicros() {
		return pixelsToMicros(0);
	}


	public long getEndMicros() {
		return pixelsToMicros(getWidth());
	}



	public abstract T getEvent(int x, int y);

	public void setTimeKeeper(TimeKeeper timeKeeper) {
		this.timeKeeper = timeKeeper;
	}

}
