package kr.gui.midigraph;

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

import kr.gui.GuiModel;
import kr.util.audio.MidiAudioClip;
import kr.util.ft.SpectrumAnalyzer;

public class ColoredScaleUI extends ScaleUI
{
	private int minNote;
	private int maxNote;
	private MidiTuneGraph comp;
	private GuiModel gm;
	private ScaleData scaleData;
	
	public static interface ScaleData
	{
		DataSet getDataSet(double microsPos);
	}
	
	public static class DataSet
	{
		public long microsStart, microsEnd;
		public byte [] noteValues;
	}

	public ColoredScaleUI(GuiModel gm, MidiTuneGraph comp, int minNote, int maxNote)
	{
		super(gm, comp, minNote, maxNote);
		this.gm = gm;
		this.comp = comp;
		this.minNote = minNote;
		this.maxNote = maxNote;
	}
	
	
	public void drawScale(Graphics2D g, int startX, int endX)
	{
		if(scaleData == null) 
		{
			super.drawScale(g, startX, endX);
			return;
		}
		
		int w = comp.getWidth();
		int h = comp.getHeight();
		double step = ((double)h) / (maxNote - minNote + 1);
		double start = step/2.;
		
		
        //double ratio = 1./guiModel.getPixelsToMicrosRatio() / clip.getMicrosToIndexRatio();
        //int addition = clip.getIndexFromMicros(nowMicros);

        double pixelsToMicrosRatio = gm.getPixelsToMicrosRatio();
		
		//offset of the edge of the screen
		double offset = gm.getNowMicros() - gm.calcNowX(w) / pixelsToMicrosRatio; 

		for(int x = startX; x < endX; )
		{
			DataSet d = scaleData.getDataSet(x/pixelsToMicrosRatio + offset);
			
			int x2 = (int) ((d.microsEnd - offset) *pixelsToMicrosRatio)+1;
			if(x2 > endX) x2 = endX;
			if(x2 == x) x2 ++;
			
			int index = d.noteValues.length-1;
			
			g.setColor(Color.RED);
			for(double i = start; i < h-step/2.; i+= step)
			{

				byte v = d.noteValues[index--]; 
				g.setColor(new Color(255,(255-v*2),(255-v*2)));
				int h1 = (int) Math.round(i - step * v / 127.); 
				int h2 = (int) Math.round(i + step * v / 127.); 
				g.fillRect(x, h1, x2 - x, h2-h1);
				
				//g.drawLine(x, (int)Math.round(i), x2, (int)Math.round(i));
			}
			
			x = x2;
		}
	}
	
	public ScaleData getScaleData() {
		return scaleData;
	}


	public void setScaleData(ScaleData scaleData) {
		this.scaleData = scaleData;
	}


}
