/*
 * Copyright (c) 2015. Ncomz. All Rights Reserved
 */

package com.ntels.kneet.v3.common.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ScrollView;

public class CustomScrollView extends ScrollView {

    private GestureDetector      mGestureDetector;
    private OnScrollViewListener onScrollViewChange;

    public CustomScrollView(Context context) {

        super(context);
        mGestureDetector = new GestureDetector(context, new YScrollDetector());
        setFadingEdgeLength(0);
    }

    public CustomScrollView(Context context, AttributeSet attrs) {

        super(context, attrs);
        mGestureDetector = new GestureDetector(context, new YScrollDetector());
        setFadingEdgeLength(0);
    }

    public CustomScrollView(Context context, AttributeSet attrs, int defStyle) {

        super(context, attrs, defStyle);
        mGestureDetector = new GestureDetector(context, new YScrollDetector());
        setFadingEdgeLength(0);
    }

    @Override protected void onScrollChanged(int l, int t, int oldl, int oldt) {

        View view = (View) getChildAt(getChildCount() - 1);
        if ( onScrollViewChange != null ) {
            onScrollViewChange.onScrollChanged(l, t, oldl, oldt);
            int diff = view.getBottom() - (getHeight() + getScrollY());
            if ( diff == 0 ) {
                onScrollViewChange.onScrollBottomDetect();
            }
            diff = view.getTop() - getScrollY();
            if ( diff == 0 ) {
                onScrollViewChange.onScrollTopDetect();
            }
        }
        super.onScrollChanged(l, t, oldl, oldt);
    }

    public OnScrollViewListener getOnScrollViewChange() {

        return onScrollViewChange;
    }

    public void setOnScrollViewChange(OnScrollViewListener onScrollViewChange) {

        this.onScrollViewChange = onScrollViewChange;
    }

    public interface OnScrollViewListener {

        void onScrollChanged(int l, int t, int oldl, int oldt);

        void onScrollBottomDetect();

        void onScrollTopDetect();
    }
    @Override public boolean onInterceptTouchEvent(MotionEvent ev) {

        return super.onInterceptTouchEvent(ev) && mGestureDetector.onTouchEvent(ev);
    }
    // Return false if we're scrolling in the x direction
    class YScrollDetector extends GestureDetector.SimpleOnGestureListener {

        @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {

            return (Math.abs(distanceY) > Math.abs(distanceX));
        }
    }
}
