import java.awt.*;

public class mapFrame extends Canvas {
asciiJam aj;
int x = 0;
int y = 0;
int z = 1;
int size = 128;
Image img=null;
boolean dragging = false;
Dimension appSz;

    public mapFrame(asciiJam ajam){
		aj = ajam;
	}

	public void drawMap(){
		int ocol = -1;
		Dimension d = this.size();
		if(img!=null){
			Graphics g = img.getGraphics();
			if(g!=null){
				for(int y=0;y<64;y++){
					int yDbl  = y<<1;
					int yDbl2 = yDbl+1;
                    int yTmp = y<<7;
		  			for(int x=0;x<128;x++){
						int i = x+(yTmp);
		  				int colIndex = aj.ta.text[env.colorOffset+i];
						if(ocol!=colIndex){
        				   g.setColor(aj.pal.palette[colIndex]);
						}
						g.drawLine(x,yDbl,x,yDbl2);
						ocol = colIndex;
		  			}
				}
			}
		}
		appSz = aj.size();
	}

	public void update(Graphics g){
		paint(g);
	}
	public void paint(Graphics g){
		g.setPaintMode();
		z = aj.ta.zoom;
		if(img==null){
		    img = aj.createImage(128,128);
 		   	g.setColor(Color.black);
		    Dimension d = this.size();
			g.fillRect(0,0,d.width,d.height);
		}
		if(img!=null){	
		    if(!dragging) drawMap();
			g.drawImage(img,1,1,null);
		}
		g.setXORMode(Color.black);
		g.setColor(Color.white);
		//g.setColor(Color.magenta);
		//Dimension appSz = aj.size();
		int rectWd = Math.min(127,(((appSz.width-133)>>3)*size)/(z<<7));
		int rectHt = Math.min(127,((appSz.height>>4)*size)/(z<<6));
		//System.out.println(x+" "+y+" "+rectWd+" "+rectHt);
		g.draw3DRect(1+x,1+y,rectWd,rectHt,true);
		g.setPaintMode();
		g.setColor(Color.black);
		g.drawRect(0,0,129,129);
	}

    public void boundPt(int mousex,int mousey){
		Dimension appSz = aj.size();
		this.z = aj.ta.zoom;
        int rectHt = ((appSz.height>>4)*size)/(64*z);
        int rectWd = (((appSz.width-133)>>3)*size)/(128*z);
        int offx = size-rectWd==0?size-rectWd:size-rectWd-1;
        int offy = size-rectHt==0?size-rectHt:size-rectHt-1;
        this.x=Math.min(Math.max(0,mousex-rectWd/2), offx);
        this.y=Math.min(Math.max(0,mousey-rectHt/2), offy);
		if(this.x<0 || this.y<0) System.out.println(this.x+" "+this.y);
	}
	public boolean handleEvent(Event e){
		if(e.id == Event.MOUSE_DRAG|| e.id == Event.MOUSE_DOWN){
		   if(e.id==Event.MOUSE_DRAG) dragging = true;
		   else{
		        appSz = aj.size();
		   		dragging = false;
		   }
		   boundPt(e.x,e.y);
		   env.setCursor(env.HAND_CURSOR,aj);
		   repaint(); //paint(getGraphics());
		}
		else if(dragging&& (e.id == Event.MOUSE_UP|| e.id==Event.MOUSE_EXIT)){
			env.setCursor(env.WAIT_CURSOR,aj);
			dragging = false;
			aj.ta.fillGrid();
			env.setCursor(aj.tool,aj);
			//env.setCursor(env.DEFAULT_CURSOR,aj);
		}
		else if(e.id == Event.MOUSE_MOVE){
			env.setCursor(env.HAND_CURSOR,aj);
		}
		return true;
	}

    public int getXIdx(){ return x; }
    public int getYIdx(){ return (int)Math.floor(y/2); }
    public int getX(){ this.z = aj.ta.zoom; return x*(z<<3); }
    public int getY(){ this.z = aj.ta.zoom; return (int)Math.floor(y/2)*(z<<4); }

}
