package net.psammead.commonist.ui;

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;
import javax.swing.event.*;

import net.psammead.commonist.util.*;

/** 
 * moves a JComponent withing a JViewport with the mouse 
 * usage: add an instance as MouseListener and MouseMotionListener to the target componente
 */
class MouseScroller extends MouseInputAdapter {
	private final JComponent	picture;
	
	private int x;
	private int y;
	
	public MouseScroller(JComponent picture) {
		this.picture = picture;
	}
	
	//public void mouseClicked(MouseEvent ev) {}
	
	@Override
	public void mousePressed(MouseEvent ev) {
		x	= ev.getX();
		y	= ev.getY();
	}
	
	//public void mouseReleased(MouseEvent ev) {}
	//public void mouseEntered(MouseEvent ev) {}
	//public void mouseExited(MouseEvent ev) {}
	
	@Override
	public void mouseDragged(MouseEvent ev) {
		Container parent	= this.picture.getParent();
		if (!(parent instanceof JViewport))	return;
		JViewport	viewPort	= (JViewport)parent;
		
		Dimension	full	= this.picture.getSize();
		Dimension	extent	= viewPort.getExtentSize();
		Point		pos		= viewPort.getViewPosition();
		
		pos.translate(
				x - ev.getX(), 
				y - ev.getY());
		
		Dimension	posLimits	= new Dimension(
				full.width  - extent.width,
				full.height - extent.height);
		pos	= UIUtil.limitToBounds(pos, posLimits);
		
//		// TODO: generic limit function in UIUtils
//		if (pos.x < 0)	pos.x	= 0;
//		if (pos.y < 0)	pos.y	= 0;
//		if (pos.x >= full.width  - extent.width)	pos.x	= full.width  - extent.width;
//		if (pos.y >= full.height - extent.height)	pos.y	= full.height - extent.height;
		
		viewPort.setViewPosition(pos);
	}
	
	//public void mouseMoved(MouseEvent ev) {}
}