/**
 * 手势/缩放功能 Helper
 * 从 EZRealPlayActivity 拆分出来，负责播放器手势监听、拖拽云台、电子放大/缩小、单击/双击事件分发
 */
package com.videogo.ui.realplay.helper;

import android.content.res.Configuration;
import android.view.MotionEvent;
import android.view.SurfaceView;
import android.view.View;

import com.videogo.exception.BaseException;
import com.videogo.realplay.RealPlayStatus;
import com.videogo.ui.common.EZBusinessTool;
import com.videogo.ui.realplay.EZRealPlayActivity;
import com.videogo.util.LogUtil;
import com.videogo.widget.CustomRect;
import com.videogo.widget.CustomTouchListener;

/**
 * 手势/缩放功能 Helper
 * 管理播放器手势监听的初始化、拖拽/缩放事件处理、电子放大双击逻辑、点击UI切换
 *
 * 直接持有 Activity 引用，生命周期与 Activity 一致，无内存泄漏风险
 */
public class GestureZoomHelper {

    private static final String TAG = "GestureZoomHelper";

    private final EZRealPlayActivity mActivity;// Activity 引用
    private boolean hasZoomIn = false;// 主画面是否已电子放大
    private boolean hasZoomIn2 = false;// 双目第二画面是否已电子放大

    public GestureZoomHelper(EZRealPlayActivity activity) {
        this.mActivity = activity;
        initTouchListener();
    }

    // region --- 公开方法 ---

    /**
     * 初始化播放器手势监听器
     */
    private void initTouchListener() {
        // 播放器手势监听器（单击、双击、拖拽、缩放）
        mActivity.mSurfaceHelper.mRealPlayTouchListener = new CustomTouchListener() {
            @Override
            public boolean canZoom(float scale) {
                return mActivity.mStatus == RealPlayStatus.STATUS_PLAY;
            }

            @Override
            public boolean canDrag(int direction) {
                if (mActivity.mStatus != RealPlayStatus.STATUS_PLAY) {
                    return false;
                }
                if (mActivity.mEZPlayer != null && mActivity.mDeviceInfo != null) {
                    // 出界判断 Out of bounds
                    if (DRAG_LEFT == direction || DRAG_RIGHT == direction) {
                        // 左移/右移出界判断 Left / right out of bounds
                        if (EZBusinessTool.isSupportPTZ(mActivity.mDeviceInfo, mActivity.mCameraInfo)) {
                            return true;
                        }
                    } else if (DRAG_UP == direction || DRAG_DOWN == direction) {
                        // 上移/下移出界判断  Move up / down to judge
                        if (EZBusinessTool.isSupportPTZ(mActivity.mDeviceInfo, mActivity.mCameraInfo)) {
                            return true;
                        }
                    }
                }
                return false;
            }

            @Override
            public void onSingleClick() {
                onRealPlaySvClick();
            }

            @Override
            public void onDoubleClick(View v, MotionEvent e) {
                LogUtil.d(TAG, "onDoubleClick:");
                changeZoomStatus(v, e);
            }

            @Override
            public void onZoom(View view, float scale) {
                LogUtil.d(TAG, "onZoom:" + scale);
                if (mActivity.mEZPlayer != null && mActivity.mDeviceInfo != null && EZBusinessTool.isSupportZoom(mActivity.mDeviceInfo, mActivity.mCameraInfo)) {
                    startZoom(view, scale);
                }
            }

            @Override
            public void onDrag(int direction, float distance, float rate) {
                LogUtil.d(TAG, "onDrag:" + direction);
                if (mActivity.mEZPlayer != null) {
                    startDrag(direction, distance, rate);
                }
            }

            @Override
            public void onEnd(View view, int mode) {
                LogUtil.d(TAG, "onEnd:" + mode);
                if (mActivity.mEZPlayer != null) {
                    stopDrag(false);
                }
                if (mActivity.mEZPlayer != null && mActivity.mDeviceInfo != null && EZBusinessTool.isSupportZoom(mActivity.mDeviceInfo, mActivity.mCameraInfo)) {
                    stopZoom(view);
                }
            }

            @Override
            public void onZoomChange(View view, float scale, CustomRect oRect, CustomRect curRect) {
                LogUtil.d(TAG, "onZoomChange:");
                try {
                    if (scale == 1) {
                        mActivity.mEZPlayer.setDisplayRegion(false, null, null);
                    } else {
                        mActivity.mEZPlayer.setDisplayRegion(true, oRect, curRect);
                    }
                } catch (BaseException e) {
                    e.printStackTrace();
                }
            }

        };

        mActivity.mSurfaceHelper.mRealPlayTouchListener2 = new CustomTouchListener() {
            @Override
            public boolean canZoom(float scale) {
                return mActivity.mStatus == RealPlayStatus.STATUS_PLAY;
            }

            @Override
            public boolean canDrag(int direction) {
                if (mActivity.mStatus != RealPlayStatus.STATUS_PLAY) {
                    return false;
                }
                if (mActivity.mEZPlayer != null && mActivity.mDeviceInfo != null) {
                    // 出界判断 Out of bounds
                    if (DRAG_LEFT == direction || DRAG_RIGHT == direction) {
                        // 左移/右移出界判断 Left / right out of bounds
                        if (EZBusinessTool.isSupportPTZ(mActivity.mDeviceInfo, mActivity.mCameraInfo)) {
                            return true;
                        }
                    } else if (DRAG_UP == direction || DRAG_DOWN == direction) {
                        // 上移/下移出界判断  Move up / down to judge
                        if (EZBusinessTool.isSupportPTZ(mActivity.mDeviceInfo, mActivity.mCameraInfo)) {
                            return true;
                        }
                    }
                }
                return false;
            }

            @Override
            public void onSingleClick() {
                onRealPlaySvClick();
            }

            @Override
            public void onDoubleClick(View v, MotionEvent e) {
                LogUtil.d(TAG, "onDoubleClick:");
                changeZoomStatus(v, e);
            }

            @Override
            public void onZoom(View view, float scale) {
                LogUtil.d(TAG, "onZoom:" + scale);
                if (mActivity.mEZPlayer != null && mActivity.mDeviceInfo != null && EZBusinessTool.isSupportZoom(mActivity.mDeviceInfo, mActivity.mCameraInfo)) {
                    startZoom(view, scale);
                }
            }

            @Override
            public void onDrag(int direction, float distance, float rate) {
                LogUtil.d(TAG, "onDrag:" + direction);
                if (mActivity.mEZPlayer != null) {
                    startDrag(direction, distance, rate);
                }
            }

            @Override
            public void onEnd(View view, int mode) {
                LogUtil.d(TAG, "onEnd:" + mode);
                if (mActivity.mEZPlayer != null) {
                    stopDrag(false);
                }
                if (mActivity.mEZPlayer != null && mActivity.mDeviceInfo != null && EZBusinessTool.isSupportZoom(mActivity.mDeviceInfo, mActivity.mCameraInfo)) {
                    stopZoom(view);
                }
            }

            @Override
            public void onZoomChange(View view, float scale, CustomRect oRect, CustomRect curRect) {
                LogUtil.d(TAG, "onZoomChange:");
                int streamId = 1;
                try {
                    if (scale == 1) {
                        mActivity.mEZPlayer.setDisplayRegion(false, null, null, streamId);
                    } else {
                        mActivity.mEZPlayer.setDisplayRegion(true, oRect, curRect, streamId);
                    }
                } catch (BaseException e) {
                    e.printStackTrace();
                }
            }

        };
    }

    /**
     * 拖拽云台
     */
    public void startDrag(int direction, float distance, float rate) {
    }

    /**
     * 停止拖拽
     */
    public void stopDrag(boolean control) {
    }

    /**
     * 开始缩放
     */
    private void startZoom(View view, float scale) {
        if (mActivity.mEZPlayer == null) {
            return;
        }
        mActivity.mTitleBarHelper.hideLandscapeTitleBar(false);
    }

    /**
     * 停止缩放
     */
    private void stopZoom(View view) {
    }

    /**
     * 点击播放视图，更新UI
     */
    public void onRealPlaySvClick() {
        if (mActivity.mEZPlayer != null && mActivity.mCameraInfo != null && mActivity.mDeviceInfo != null) {
            if (mActivity.mDeviceInfo.getStatus() != 1) {
                return;
            }
            if (mActivity.mOrientation == Configuration.ORIENTATION_PORTRAIT) {
                setRealPlayControlRlVisibility();
            } else {
                setRealPlayFullOperateBarVisibility();
            }
        } else if (mActivity.mRtspUrl != null) {
            setRealPlayControlRlVisibility();
        }
    }

    // endregion

    // region --- 竖屏/横屏 点击UI切换 ---

    /**
     * 竖屏时点击播放视图，更新UI
     */
    private void setRealPlayControlRlVisibility() {
        if (mActivity.mLandscapeTitleBar.getVisibility() == View.VISIBLE || mActivity.mRealPlayControlRl.getVisibility() == View.VISIBLE) {
            mActivity.mLandscapeTitleBar.setVisibility(View.GONE);
        } else {
            mActivity.mRealPlayControlRl.setVisibility(View.VISIBLE);
            if (mActivity.mOrientation == Configuration.ORIENTATION_LANDSCAPE) {
                if (!mActivity.mVoiceTalkHelper.isOnTalk() && !mActivity.mPtzHelper.isOnPtz()) {
                    mActivity.mLandscapeTitleBar.setVisibility(View.VISIBLE);
                }
            } else {
                mActivity.mLandscapeTitleBar.setVisibility(View.GONE);
            }
            mActivity.mControlDisplaySec = 0;
        }
    }

    /**
     * 横屏时点击播放视图，更新UI
     */
    private void setRealPlayFullOperateBarVisibility() {
        if (mActivity.mLandscapeTitleBar.getVisibility() == View.VISIBLE) {// 可见时隐藏相关UI
            mActivity.mLandscapeTitleBar.setVisibility(View.GONE);
        } else {// 不可见时显示导航栏
            if (!mActivity.mVoiceTalkHelper.isOnTalk() && !mActivity.mPtzHelper.isOnPtz()) {
                mActivity.mLandscapeTitleBar.setVisibility(View.VISIBLE);
            }
            mActivity.mControlDisplaySec = 0;
        }
    }

    // endregion

    // region --- 电子放大 ---

    /**
     * 未放大情况下，以双击点位置为坐标原点将画面放大2倍
     * 已放大情况下，取消画面放大效果
     */
    @SuppressWarnings("PointlessArithmeticExpression")
    private void changeZoomStatus(View v, MotionEvent e) {
        int streamId = (v == mActivity.mSurfaceHelper.mRealPlaySv) ? 0 : 1;
        if (streamId == 0) {
            if (hasZoomIn) {
                int invalid = -1;
                mActivity.mEZPlayer.setDisplayRegion(invalid, invalid, invalid, invalid, streamId);
            } else {
                setDisplayRegion(v, e, streamId);
            }
            hasZoomIn = !hasZoomIn;
        } else if (streamId == 1) {
            if (hasZoomIn2) {
                int invalid = -1;
                mActivity.mEZPlayer.setDisplayRegion(invalid, invalid, invalid, invalid, streamId);
            } else {
                setDisplayRegion(v, e, streamId);
            }
            hasZoomIn2 = !hasZoomIn2;
        }
    }

    /**
     * 设置电子放大区域
     */
    private void setDisplayRegion(View v, MotionEvent e, int streamId) {
        // x轴方向
        double xOffsetRateOfAnchor = (e.getX() / (double) v.getWidth()) - 0.5;
        int left = (int) (mActivity.mVideoWidth / 4 * 1 + xOffsetRateOfAnchor * mActivity.mVideoWidth);
        int right = (int) (mActivity.mVideoWidth / 4 * 3 + +xOffsetRateOfAnchor * mActivity.mVideoWidth);
        if (left < 0) { // left超出边界，需要修正
            left = 0;
            right = mActivity.mVideoWidth / 2;
        }
        if (right > mActivity.mVideoWidth) { // right超出边界，需要修正
            right = mActivity.mVideoWidth;
            left = mActivity.mVideoWidth / 2;
        }
        // y轴方向
        double yOffsetRateOfAnchor = (e.getY() / (double) v.getHeight()) - 0.5;
        int top = (int) (mActivity.mVideoHeight / 4 * 1 + yOffsetRateOfAnchor * mActivity.mVideoHeight);
        int bottom = (int) (mActivity.mVideoHeight / 4 * 3 + +yOffsetRateOfAnchor * mActivity.mVideoHeight);
        if (top < 0) { // top超出边界，需要修正
            top = 0;
            bottom = mActivity.mVideoHeight / 2;
        }
        if (bottom > mActivity.mVideoHeight) { // bottom超出边界，需要修正
            bottom = mActivity.mVideoHeight;
            top = mActivity.mVideoHeight / 2;
        }
        // 设置坐标
        mActivity.mEZPlayer.setDisplayRegion(left, top, right, bottom, streamId);
    }

    // endregion
}
