package com.android.launcher3.views;

import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Scroller;

import com.android.launcher3.util.Logger;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.view.ViewCompat;
import androidx.customview.widget.ViewDragHelper;

public class SwipeUpFinishLayout extends RelativeLayout {


    private static final String TAG = "SwipeUpFinishLayout";

    private int touchSlop;

    private float mScrollThreshold=0.3f;

    private View mContentView;

    private Activity activity;

    private float mScrollPercent;

    private float mScrimOpacity;

    private ViewDragHelper mDragHelper;

    private boolean mEnable = true;

    private int mContentLeft,mContentTop;
    public SwipeUpFinishLayout(Context context) {
        this(context, null);
    }

    public SwipeUpFinishLayout(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public SwipeUpFinishLayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);



        SwipeViewDragHelper swipeViewDragHelper = new SwipeViewDragHelper();
        mDragHelper = ViewDragHelper.create(this, swipeViewDragHelper);
        mDragHelper.setEdgeTrackingEnabled(ViewDragHelper.EDGE_BOTTOM);

    }

    public void attachActivity(Activity activity) {
        this.activity = activity;
        TypedArray a = activity.getTheme().obtainStyledAttributes(new int[]{
                android.R.attr.windowBackground
        });
        int background = a.getResourceId(0, 0);
        a.recycle();

        ViewGroup decor = (ViewGroup) activity.getWindow().getDecorView();
        ViewGroup decorChild = (ViewGroup) decor.getChildAt(0);
        decorChild.setBackgroundResource(background);
        decor.removeView(decorChild);
        addView(decorChild);
        mContentView=decorChild;
        decor.addView(this);
    }

    public void setEnable(boolean mEnable) {
        this.mEnable = mEnable;
    }

    private boolean mInLayout=false;
    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        mInLayout = true;
        if (mContentView != null)
            mContentView.layout(mContentLeft, mContentTop,
                    mContentLeft + mContentView.getMeasuredWidth(),
                    mContentTop + mContentView.getMeasuredHeight());
        mInLayout = false;
    }

    @Override
    public void requestLayout() {
        if (!mInLayout) {
            super.requestLayout();
        }
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent event) {

        if (!mEnable) {
            return false;
        }
        try {
            return mDragHelper.shouldInterceptTouchEvent(event);
        } catch (ArrayIndexOutOfBoundsException e) {
            // FIXME: handle exception
            // issues #9
            return false;
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (!mEnable) {
            return false;
        }
        mDragHelper.processTouchEvent(event);
        return true;
    }


    private class SwipeViewDragHelper extends ViewDragHelper.Callback {

        @Override
        public boolean tryCaptureView(@NonNull View child, int i) {

            boolean  directionCheck = !mDragHelper
                    .checkTouchSlop(ViewDragHelper.DIRECTION_HORIZONTAL, i);
            return directionCheck;
        }

        @Override
        public int getViewVerticalDragRange(@NonNull View child) {
            return ViewDragHelper.EDGE_BOTTOM;
        }

        @Override
        public int clampViewPositionVertical(@NonNull View child, int top, int dy) {
            int ret = Math.min(0, Math.max(top, -child.getHeight()));

            return ret;
        }

        @Override
        public void onViewReleased(@NonNull View releasedChild, float xvel, float yvel) {
            final int childHeight = releasedChild.getHeight();

            int left = 0, top = 0;

            top = yvel < 0 || yvel == 0 && mScrollPercent > mScrollThreshold ? -(childHeight
                    ) : 0;


            mDragHelper.settleCapturedViewAt(left, top);
            invalidate();
        }

        @Override
        public void onViewPositionChanged(@NonNull View changedView, int left, int top, int dx, int dy) {
            super.onViewPositionChanged(changedView, left, top, dx, dy);

            mScrollPercent = Math.abs((float) top
                    / (mContentView.getHeight()));

            mContentLeft = left;
            mContentTop = top;
            invalidate();
            if (mScrollPercent >= 1) {
               if (activity!=null&&!activity.isFinishing()){
                   activity.finish();
               }
            }

        }
    }


    @Override
    public void computeScroll() {
        mScrimOpacity= 1 - mScrollPercent;
        if (mDragHelper.continueSettling(true)) {
            ViewCompat.postInvalidateOnAnimation(this);
        }
    }
}
