package infomat.view.picture;

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

import infomat.view.grouping.settings.GroupingColoring;

/**
 * Draws guiding lines for the mouse pointer.
 *
 * @version          080724
 * @author           Magnus Rosell
 */
public class Guide{

    private SparsePicture sparsePicture;
    private Graphics g;

    // The previous position
    private int oldX=-1;
    private int oldY=-1;

    // The rectangle start
    private int rectX=-1;
    private int rectY=-1;

    private boolean draw=true; // If it should be drawed
    private boolean drawable=false; // If it's possible to draw it
    //    private boolean drawX=true;
    //    private boolean drawY=true;

    public Guide(SparsePicture sparsePicture){
	this.sparsePicture=sparsePicture;
	g=sparsePicture.getGraphics();
	//	enter();
    }

    public void toggleDraw(){
	if(draw){
	    reset();
	}
	setDraw(!draw);
    }

    public void setDraw(boolean draw){
	if(!draw && this.draw && oldX!=-1){
	    reset();
	}
	this.draw=draw;
    }
    
    protected void setRect(int rectX, int rectY){
	if(oldX!=-1){
	    unDraw();
	    oldX=-1;
	    oldY=-1;
	}
	this.rectX=rectX;
	this.rectY=rectY;
    }

    protected void noRect(int x, int y){
	if(rectX!=-1){
	    reset();
	    //	    unDraw();
	    //	    draw(x,y);
	}
    }

    protected void draw(int x, int y){
	if(!draw || !drawable)
	    return;
	
	g=sparsePicture.getGraphics();
	if(oldX!=-1){
	    unDraw();
	}
	g.setXORMode(GroupingColoring.getBackgroundColor());

	if(rectX!=-1){
	    int firstX=rectX;
	    int dx = x-rectX;
	    if(x<rectX){
		firstX=x;
		dx = rectX-x;
	    }
	    int firstY=rectY;
	    int dy = y-rectY;
	    if(y<rectY){
		firstY=y;
		dy = rectY-y;
	    }
	    g.drawRect(firstX, firstY, dx, dy);
	}else{
	    g.drawLine(x, 0, x, sparsePicture.getHeight());
	    g.drawLine(0, y, sparsePicture.getWidth(), y);
	}

	oldX=x;
	oldY=y;
    }

    protected void unDraw(){
	if(!draw || !drawable)
	    return;

	g=sparsePicture.getGraphics();
	g.setXORMode(GroupingColoring.getBackgroundColor());

	if(rectX!=-1){
	    int firstX=rectX;
	    int dx = oldX-rectX;
	    if(oldX<rectX){
		firstX=oldX;
		dx = rectX-oldX;
	    }
	    int firstY=rectY;
	    int dy = oldY-rectY;
	    if(oldY<rectY){
		firstY=oldY;
		dy = rectY-oldY;
	    }
	    g.drawRect(firstX, firstY, dx, dy);
	}else{
	    g.drawLine(oldX, 0, oldX, sparsePicture.getHeight());
	    g.drawLine(0, oldY, sparsePicture.getWidth(), oldY);
	}
    }

    protected void exit(){
	unDraw();
	oldX=-1;
	oldY=-1;
	drawable=false;
    }

    protected void enter(){
	drawable=true;
    }

    protected void reset(){
	unDraw();
	oldX=-1;
	oldY=-1;
	rectX=-1;
	rectY=-1;
    }

}
