package jp.agentec.abook.abv.ui.common.listener;

import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.animation.OvershootInterpolator;
import android.widget.HorizontalScrollView;
import android.widget.Scroller;

public class ABVScrollPager implements OnTouchListener
{
 // The class encapsulates scrolling.(Overshoot)
 private Scroller scroller;
 // The task make scroll view scrolled.
 private Runnable task;

 public int positionWidth = 0;
 private HorizontalScrollView scrollView;

 private OnScrollerTransferListener mOnScrollerTransferListener;

 public interface OnScrollerTransferListener {
    void OnScrollerTransferListener();
 }

 public void setScrollerTransferListener(OnScrollerTransferListener listener) {
	 mOnScrollerTransferListener = listener;
 }
 
 public ABVScrollPager(HorizontalScrollView aScrollView)
 {
	 scrollView = aScrollView;
	 scroller = new Scroller(scrollView.getContext(), new OvershootInterpolator());
	 task = new Runnable()
	  {
		   @Override
		   public void run()
		   {
			    scroller.computeScrollOffset();
			    scrollView.scrollTo(scroller.getCurrX(), 0);

               if (scroller.isFinished()) {
                   mOnScrollerTransferListener.OnScrollerTransferListener();
               } else {
                   scrollView.post(this);
               }
		   }
	  };
 }

 public void scrollChange(int selectSeekBar) {

	scroller.forceFinished(true);
	scrollView.removeCallbacks(task);
	scroller.startScroll(scrollView.getScrollX(), 0,(scrollView.getWidth() * (selectSeekBar-1))- scrollView.getScrollX(),0 , 100);	

	positionWidth = (scrollView.getWidth() * (selectSeekBar-1));
	scrollView.post(task);
	
 }
 
 public void scrollTo(int x, int y) {
	 positionWidth = x;
	 scrollView.scrollTo(x, y);
 }
 @Override
 public boolean onTouch(View v, MotionEvent event)
 {
	  scroller.forceFinished(true);
	  scrollView.removeCallbacks(task);

	 if (event.getAction() == MotionEvent.ACTION_UP)
	 {
		 
		if (positionWidth + 150 < scrollView.getScrollX()) {
			positionWidth += scrollView.getWidth();
		}else if (positionWidth - 150 > scrollView.getScrollX()) {
			positionWidth -= scrollView.getWidth();
		}		
		
	   scroller.startScroll(scrollView.getScrollX(), 0, positionWidth - scrollView.getScrollX(), 100);
	   
	   scrollView.post(task);
	   return true;
  }

	  return false;
 
 }
} 




