/*******************************************************************************
 * Copyright (c) 2010 Attila Kovacs <attila_kovacs@post.harvard.edu>.
 * All rights reserved. 
 * 
 * This file is part of crush.
 * 
 *     crush is free software: you can redistribute it and/or modify
 *     it under the terms of the GNU General Public License as published by
 *     the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 * 
 *     crush is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU General Public License for more details.
 * 
 *     You should have received a copy of the GNU General Public License
 *     along with crush.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * Contributors:
 *     Attila Kovacs <attila_kovacs@post.harvard.edu> - initial API and implementation
 ******************************************************************************/
// Copyright (c) 2007 Attila Kovacs 

package crush.gui;

import java.awt.*;
import javax.swing.*;

import crush.gui.colorscheme.CameraLike;

import java.text.*;

public class ColorMapPanel extends JPanel {
    /**
	 * 
	 */
	private static final long serialVersionUID = 8063198567194226851L;

	double[][] data;
 
    ColorScheme colorScheme;

    int borderheight = 1, borderwidth = 1;
    int spacing=1, nx, ny;
    double stretch=1, level=0;

    boolean autoscaled=false;

    double min, max;
    DecimalFormat df = new DecimalFormat("0.###");

    public ColorMapPanel() {
	setDefaults();
    }

    public ColorMapPanel(double[][] map) {
	data=map;
	setDefaults();
    }

    public void setDefaults() {
	colorScheme=new CameraLike();
	setRange(0, 1);
    }
	
    @Override
	public void paintComponent(Graphics g) {
	super.paintComponent(g);
	draw(g);
    }

    public void draw(Graphics g){
	nx = data[0].length;
	ny = data.length;

	float dw = (float) (getWidth()-2*borderwidth)/nx;
	float dh = (float) (getHeight()-2*borderheight)/ny;
	
	int nextw=0, nexth=0;

	for(int i=0; i<ny; i++) {
	    for(int j=0; j<nx; j++) {
		int w=(int) (j*dw+0.5) + borderwidth;
		int h=(int) (i*dh+0.5) + borderheight;
		nextw=(int) ((j+1)*dw+0.5) + borderwidth;
		nexth=(int) ((i+1)*dh+0.5) + borderheight;
		int Dw=nextw-w-spacing;
		int Dh=nexth-h-spacing;
		
		float value = (float) (stretch*(data[i][j]-level));
		g.setColor(colorScheme.getColor(value));
		g.fillRect(w, h, Dw, Dh );
		
		Thread.yield();
	    }
	}
	
    }
    
    public void setRange(double min, double max) {
	level=min;
	stretch=1.0/(max-min);
    }

    public void setBorder(int xborder, int yborder) {
	borderwidth = xborder;
	borderheight = yborder;
    }
	
}
   

// 02.11.08  Added crosshairs



