/* $Id: RectangleMode.java 475 2011-12-02 08:46:54Z ohura $ */
package smart_gs.drawing_tool.drawing_mode;

import java.awt.Cursor;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;


import smart_gs.drawing_tool.SpreadCanvas;
//import smart_gs.drawing_tool.state.DefaultState;
import smart_gs.drawing_tool.state.DefaultState;
import smart_gs.drawing_tool.view.RectangleView;
import smart_gs.drawing_tool.view.View;
import smart_gs.logical.region.RectangleRegion;
import smart_gs.swingui.GSMouseEvent;

public class RectangleMode extends DrawingModeAdapter{
	
	private static Mode singleton = new RectangleMode();
	
	private Point2D start;
	private Point2D end;
	
	public static Mode getInstance(){
		return singleton;
	}
	
	@Override
	public void mousePressed(GSMouseEvent e, SpreadCanvas canvas) {
		super.mousePressed(e, canvas);
		this.start = e.getPoint();
		setCursor(canvas);
	}
	@Override
	public void mouseDragged(GSMouseEvent e,SpreadCanvas canvas) {
		super.mouseDragged(e,canvas);
		this.end = e.getPoint();
		setCursor(canvas);
	}
	
	@Override
	public void mouseReleased(GSMouseEvent e, SpreadCanvas canvas) {
		super.mouseReleased(e, canvas);
		if(start == null || end == null){
			return ;
		}
		canvas.addRegion(new RectangleRegion(canvas.getSpread(),adjustRect(start.getX(), start.getY())));
		
		this.start = null;
		this.end = null;
		/*
		 * カーソルをrectangleから元の状態に戻している
		 * 
		 */
//		DefaultState.getInstance().setMode(DefaultDrawingMode.getInstance());
		setCursor(canvas);
	}
	@Override
	public void paint(Graphics g,SpreadCanvas canvas) {
		super.paint(g,canvas);
		if(this.start ==null || this.end == null){
			return;
		}
		double ratio = canvas.getImageLabel().getRatio();
		double gapX = canvas.getImageLabel().getGapWidth();
		double gapY = canvas.getImageLabel().getGapHeight();
		View view = new RectangleView(adjustRect(start.getX(), start.getY())).enlargedView(ratio, gapX, gapY);
		
		view.draw((Graphics2D)g);
	}
	private Rectangle2D adjustRect(double sx, double sy){
				double width, height;
		double startX, startY;
		
		if(start.getX() > end.getX()){
			startX = end.getX();
			width = start.getX() - end.getX();
		}
		else{
			startX = start.getX();
			width = end.getX() - start.getX();
		}
		if(start.getY() > end.getY()){
			startY = end.getY();
			height = start.getY() - end.getY();
		}
		else{
			startY = start.getY();
			height= end.getY() - start.getY();
		}
		return new Rectangle2D.Double(startX,startY,width,height);
	}
}
