package adecWatt.view;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Rectangle;
import javax.swing.JComponent;
import javax.swing.JScrollPane;

import misc.DimensionDouble;

import adecWatt.model.unit.Workspace;

@SuppressWarnings ("serial") public class JScrollPaneWorkspace extends JScrollPane {

    static public final boolean	HORIZONTAL	= true;
    static public final boolean	VERTICAL	= false;
    static public final int	SIZE		= 16;
    static public final Color	BG		= Color.LIGHT_GRAY;
    static public final int	TICK_LENGTH	= 5;

    private JWorkspaceView<?> jWorkspaceView;
    private JRule horizontalJRule = new JRule (HORIZONTAL);
    private JRule verticalJRule = new JRule (VERTICAL);

    public JWorkspaceView<?> getJWorkspaceView () { return jWorkspaceView; }
    public Workspace getWorkspace () { return jWorkspaceView.getWorkspace (); }

    public JScrollPaneWorkspace (JWorkspaceView<?> jWorkspaceView) {
	super (jWorkspaceView, VERTICAL_SCROLLBAR_AS_NEEDED, HORIZONTAL_SCROLLBAR_AS_NEEDED);
	this.jWorkspaceView = jWorkspaceView;
	setColumnHeaderView (horizontalJRule);
	setRowHeaderView (verticalJRule);
    }

    void updateScale () {
	horizontalJRule.repaint ();
	verticalJRule.repaint ();
    }

    public class JRule extends JComponent {
	public boolean horizontal;
	public JRule (boolean horizontal) {
	    this.horizontal = horizontal;
	    setPreferredSize (new Dimension (SIZE, SIZE));
	}

	protected void paintComponent (Graphics g) {
	    Rectangle viewRect = getViewport ().getViewRect ();
	    double scale = jWorkspaceView.getScale ();
	    DimensionDouble realSize = jWorkspaceView.getRealSize ();

	    int minTick = (int) Math.round ((horizontal ? viewRect.x : viewRect.y)/scale);
	    int maxTick =
		(int) Math.round (Math.min ((horizontal ? realSize.width : realSize.height),
					    (horizontal ? viewRect.x+viewRect.width : viewRect.y+viewRect.height)/scale));

	    Rectangle drawHere = g.getClipBounds ();
	    g.setColor (BG);
	    g.fillRect (drawHere.x, drawHere.y, drawHere.width, drawHere.height);
	    g.setFont (new Font ("SansSerif", Font.PLAIN, 8));
	    g.setColor (Color.black);

	    for (int i = minTick; i <= maxTick; i += 1) {
		int p = (int) (i*scale - (horizontal ? viewRect.x : viewRect.y));
		if (horizontal)
		    g.drawLine (p, SIZE-1, p, SIZE-TICK_LENGTH-1);
		else
		    g.drawLine (SIZE-1, p, SIZE-TICK_LENGTH-1, p);
		String text = Integer.toString (i);
		if (i == 0) {
		    text += "m";
		    if (horizontal)
			g.drawString (text, p+2, 8);
		    else
			g.drawString (text, 1, p+10);
		    continue;
		}
		if (horizontal)
		    g.drawString (text, p-3, 8);
		else
		    g.drawString (text, 0, p+3);
	    }
	}
    }
}
