package com.videogo.ui.realplay.helper;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

import com.videogo.realplay.RealPlayStatus;
import com.videogo.ui.realplay.EZRealPlayActivity;

/**
 * 屏幕事件Helper
 * 管理息屏/亮屏广播的注册与注销，锁屏时自动停止预览并关闭弹窗
 */
public class ScreenEventHelper {

    private final EZRealPlayActivity mActivity;
    private BroadcastReceiver mBroadcastReceiver;

    public ScreenEventHelper(EZRealPlayActivity activity) {
        mActivity = activity;
    }

    /**
     * 注册息屏广播
     */
    public void registerScreenReceiver() {
        mBroadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (Intent.ACTION_SCREEN_OFF.equals(intent.getAction())) {
                    // 锁屏时，关闭云台和对讲弹出框，并停止预览
                    mActivity.mPtzHelper.closePtzPopupWindow();
                    mActivity.mVoiceTalkHelper.closeTalkPopupWindow(true);
                    if (mActivity.mStatus != RealPlayStatus.STATUS_STOP) {
                        mActivity.playerStopRealPlay();
                        mActivity.mStatus = RealPlayStatus.STATUS_PAUSE;
                        mActivity.setRealPlayResult(false);
                    }
                }
            }
        };
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_USER_PRESENT);// 当解除锁屏的时候
        filter.addAction(Intent.ACTION_SCREEN_OFF);// 当按下电源键，屏幕变黑的时候
        mActivity.registerReceiver(mBroadcastReceiver, filter);
    }

    /**
     * 注销息屏广播
     */
    public void unregisterScreenReceiver() {
        if (mBroadcastReceiver != null) {
            // 取消锁屏广播的注册 Cancel the registration of the lock screen broadcast
            mActivity.unregisterReceiver(mBroadcastReceiver);
            mBroadcastReceiver = null;
        }
    }
}
