package com.baidu.ai.sample.view;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.PopupWindow;

import com.baidu.ai.sample.R;
import com.baidu.ai.sample.util.UIUtils;

public class PopActionView {
    private static final String TAG = "PopActionView";
    private Context mContext;
    private PopupWindow mWindow;
    private View mRootView;
    private int mAnchorX;
    private int mAnchorY;
    public PopActionView(Context context) {
        mContext = context;
    }

    public void showView(View view) {
        if (mWindow == null) {
            onCreate(view);
        } else {
            show(view);
        }
    }

    public void dismiss() {
        if (mWindow != null) {
            mWindow.dismiss();
        }
    }

    public View getWindow() {
        return mRootView;
    }

    private void onCreate(View view) {
        Context context = view.getContext();
        mRootView = LayoutInflater.from(context).inflate(R.layout.tools_popview, null);
        mWindow = new PopupWindow(mRootView, UIUtils.dp2px(context, 180), UIUtils.dp2px(context, 130), true);
        mWindow.setOutsideTouchable(true);
        mWindow.setBackgroundDrawable(mContext.getDrawable(android.R.color.transparent));
        // 获取锚点的位置和高度
        int[] location = new int[2];
        view.getLocationOnScreen(location);
        int anchorX = location[0];
        int anchorY = location[1];
        anchorY = anchorY - mRootView.getMeasuredHeight() - UIUtils.dp2px(context, 135);
        mWindow.showAtLocation(view,  0, anchorX, anchorY);
        mAnchorX = anchorX;
        mAnchorY = anchorY;
        Log.i(TAG, "anchorX:" + anchorX + ",anchorY: " + anchorY + ", h:" + (mRootView.getMeasuredHeight()));
        mRootView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if (motionEvent.getAction() == MotionEvent.ACTION_OUTSIDE) {
                    mWindow.dismiss();
                    return true;
                } else {
                    return false;
                }
            }
        });
    }

    private void show(View view) {
        mWindow.showAtLocation(view,  0, mAnchorX, mAnchorY);
    }
}
