/**
 * 屏幕旋转/全屏 Helper
 * 从 EZRealPlayActivity 拆分出来，负责屏幕方向控制、全屏切换、播放视图布局、操控栏UI更新等逻辑
 */
package com.videogo.ui.realplay.helper;

import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;

import com.videogo.constant.Constant;
import com.videogo.realplay.RealPlayStatus;
import com.videogo.ui.common.ScreenOrientationHelper;
import com.videogo.ui.realplay.EZRealPlayActivity;
import com.videogo.util.LogUtil;
import com.videogo.util.Utils;

import ezviz.ezopensdk.R;

/**
 * 屏幕旋转/全屏 Helper
 * 管理屏幕方向切换、全屏/退出全屏、播放视图布局计算、操控栏UI根据方向更新
 * <p>
 * 直接持有 Activity 引用，生命周期与 Activity 一致，无内存泄漏风险
 */
public class OrientationHelper {

    private static final String TAG = "OrientationHelper";

    private final EZRealPlayActivity mActivity;// Activity 引用
    private ScreenOrientationHelper mScreenOrientationHelper;// 屏幕方向控制器
    private int mForceOrientation = 0;// 强制方向（0=不强制）

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

    /**
     * 初始化 ScreenOrientationHelper
     */
    public void initScreenOrientationHelper(ScreenOrientationHelper helper) {
        this.mScreenOrientationHelper = helper;
    }

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

    /**
     * 更新屏幕方向策略
     * 根据当前播放状态和对讲状态，决定屏幕方向是否跟随传感器
     */
    public void updateOrientation() {
        if (mActivity.mVoiceTalkHelper.isOnTalk()) {
            if (mActivity.mEZPlayer != null && mActivity.mDeviceInfo != null && com.videogo.ui.common.EZBusinessTool.isSupportTalk(mActivity.mDeviceInfo, mActivity.mCameraInfo) != com.videogo.openapi.EZConstants.EZTalkbackCapability.EZTalkbackNoSupport) {
                setOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
            } else {
                setForceOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            }
        } else {
            if (mActivity.mStatus == RealPlayStatus.STATUS_PLAY) {
                setOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
            } else {
                if (mActivity.mOrientation == Configuration.ORIENTATION_PORTRAIT) {
                    setOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                } else {
                    setOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
                }
            }
        }
    }

    /**
     * 设置屏幕方向
     *
     * @param sensor 方向值（SCREEN_ORIENTATION_SENSOR / SCREEN_ORIENTATION_PORTRAIT）
     */
    private void setOrientation(int sensor) {
        if (mForceOrientation != 0) {
            LogUtil.d(TAG, "setOrientation mForceOrientation:" + mForceOrientation);
            return;
        }

        if (sensor == ActivityInfo.SCREEN_ORIENTATION_SENSOR) mScreenOrientationHelper.enableSensorOrientation();
        else mScreenOrientationHelper.disableSensorOrientation();
    }

    /**
     * 设置强制方向
     *
     * @param orientation 强制的方向值（0=取消强制）
     */
    public void setForceOrientation(int orientation) {
        if (mForceOrientation == orientation) {
            LogUtil.d(TAG, "setForceOrientation no change");
            return;
        }
        mForceOrientation = orientation;
        if (mForceOrientation != 0) {
            if (mForceOrientation != mActivity.mOrientation) {
                if (mForceOrientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
                    mScreenOrientationHelper.portrait();
                } else {
                    mScreenOrientationHelper.landscape();
                }
            }
            mScreenOrientationHelper.disableSensorOrientation();
        } else {
            updateOrientation();
        }
    }

    /**
     * 屏幕方向改变后的处理
     * 由 Activity 的 onConfigurationChanged 调用
     */
    public void onOrientationChanged() {
        setRealPlaySvLayout();

        updateOperatorUI();
        mActivity.mVoiceTalkHelper.updateTalkUI();
        mActivity.mPtzHelper.updatePtzUI();
    }

    /**
     * 全屏切换
     *
     * @param enable true-进入全屏  false-退出全屏
     */
    public void fullScreen(boolean enable) {
        if (enable) {
            WindowManager.LayoutParams lp = mActivity.getWindow().getAttributes();
            lp.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
            mActivity.getWindow().setAttributes(lp);
            mActivity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
        } else {
            WindowManager.LayoutParams attr = mActivity.getWindow().getAttributes();
            attr.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
            mActivity.getWindow().setAttributes(attr);
            mActivity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
        }
    }

    /**
     * 设置播放器视图布局（根据屏幕方向计算宽高）
     */
    public void setRealPlaySvLayout() {
        final int screenWidth = mActivity.mLocalInfo.getScreenWidth();
        final int screenHeight = (mActivity.mOrientation == Configuration.ORIENTATION_PORTRAIT) ?
                (mActivity.mLocalInfo.getScreenHeight() - mActivity.mLocalInfo.getNavigationBarHeight()) :
                mActivity.mLocalInfo.getScreenHeight();
        final LayoutParams realPlaySvlp = Utils.getPlayViewLp(mActivity.mRealRatio, mActivity.mOrientation,
                mActivity.mLocalInfo.getScreenWidth(),
                (int) (mActivity.mLocalInfo.getScreenWidth() * Constant.LIVE_VIEW_RATIO), screenWidth, screenHeight);

        LayoutParams svLp = new LayoutParams(realPlaySvlp.width, realPlaySvlp.height);
        svLp.addRule(RelativeLayout.CENTER_HORIZONTAL);

        mActivity.mPlayWindowVg.setLayoutParams(svLp);

        if (mActivity.mRtspUrl != null) {
            LinearLayout.LayoutParams realPlayPlayRlLp = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
                    LayoutParams.MATCH_PARENT);
            realPlayPlayRlLp.gravity = Gravity.CENTER;
            mActivity.mRealPlayPlayRl.setLayoutParams(realPlayPlayRlLp);
        }
        mActivity.mSurfaceHelper.mRealPlayTouchListener.setSacaleRect(Constant.MAX_SCALE, 0, 0, realPlaySvlp.width,
                realPlaySvlp.height);
        if (mActivity.isMultiChannelDevice) {
            mActivity.mSurfaceHelper.mRealPlayTouchListener2.setSacaleRect(Constant.MAX_SCALE, 0, 0,
                    realPlaySvlp.width, realPlaySvlp.height);
        }
    }

    /**
     * 更新操控栏UI（根据屏幕方向切换竖屏/横屏的UI可见性）
     */
    public void updateOperatorUI() {
        if (mActivity.mOrientation == Configuration.ORIENTATION_PORTRAIT) {
            fullScreen(false);
            updateOrientation();
            mActivity.mPortraitTitleBar.setVisibility(View.VISIBLE);
            mActivity.mLandscapeTitleBar.setVisibility(View.GONE);
            mActivity.mRealPlayControlRl.setVisibility(View.VISIBLE);
            if (mActivity.mRtspUrl == null) {
                mActivity.mRealPlayPage.setBackgroundColor(mActivity.getResources().getColor(R.color.common_bg));
                mActivity.mRealPlayOperateBar.setVisibility(View.VISIBLE);
                mActivity.mCaptureRecordHelper.updateRecordBtnVisibility();
            }
        } else {
            fullScreen(true);
            mActivity.mPortraitTitleBar.setVisibility(View.GONE);
            // hide the
            mActivity.mRealPlayControlRl.setVisibility(View.GONE);
            if (!mActivity.mVoiceTalkHelper.isOnTalk() && !mActivity.mPtzHelper.isOnPtz()) {
                mActivity.mLandscapeTitleBar.setVisibility(View.VISIBLE);
            }
            if (mActivity.mRtspUrl == null) {
                mActivity.mRealPlayOperateBar.setVisibility(View.GONE);
                mActivity.mRealPlayPage.setBackgroundColor(mActivity.getResources().getColor(R.color.black_bg));
            }
        }

        if (mActivity.mStatus == RealPlayStatus.STATUS_START) {
            mActivity.mTitleBarHelper.showControlRlAndFullOperateBar();
        }
    }

    /**
     * 返回键处理横屏转竖屏
     *
     * @return true-已处理（当前横屏，转为竖屏）  false-未处理（当前竖屏）
     */
    public boolean handleBackPressed() {
        if (mActivity.getResources().getConfiguration().orientation != Configuration.ORIENTATION_PORTRAIT) {
            mScreenOrientationHelper.portrait();
            return true;
        }
        return false;
    }

    /**
     * onStop 时通知 ScreenOrientationHelper
     */
    public void postOnStop() {
        if (mScreenOrientationHelper != null) {
            mScreenOrientationHelper.postOnStop();
        }
    }

    /**
     * 销毁时释放资源
     */
    public void release() {
        mScreenOrientationHelper = null;
    }

    // endregion

    // region --- 状态查询 ---

    /**
     * 获取强制方向值
     */
    public int getForceOrientation() {
        return mForceOrientation;
    }

    /**
     * 获取 ScreenOrientationHelper 实例
     */
    public ScreenOrientationHelper getScreenOrientationHelper() {
        return mScreenOrientationHelper;
    }

    // endregion
}
