package com.meeting.demo.externalframe;

import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.SensorManager;
import android.view.LayoutInflater;
import android.view.OrientationEventListener;
import android.view.SurfaceView;
import android.view.View;
import android.widget.LinearLayout;

import com.meeting.demo.R;
import com.huawei.hwmfoundation.eventbus.ApplicationState;
import com.huawei.hwmlogger.HCLog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * 第三方采集加载SurfaceView的悬浮窗
 */
public class PushExternalFrameFlowWindow extends LinearLayout {

    private static final String TAG = PushExternalFrameFlowWindow.class.getSimpleName();
    private int mViewWidth;
    private int mViewHeight;
    private Context mContext;
    private SurfaceView mCameraSurface;
    private CameraSurfaceHolder mCameraSurfaceHolder = new CameraSurfaceHolder();
    private OrientationEventListener mOrientationEventListener;
    /**
     * 当前角度
     */
    private static int curOriginalOrientation = 1;

    /**
     * 未知角度，无象限所属
     */
    private static final int ORIENTATION_UNKNOWN = 1;

    /**
     * 竖屏象限（摄像头在上）
     */
    private static final int ORIENTATION_PORTRAIT_UP = 1;

    /**
     * 横屏象限（摄像头在右）
     */
    private static final int ORIENTATION_LANDSCAPE_RIGHT = 2;

    /**
     * 横屏象限（摄像头在左）
     */
    private static final int ORIENTATION_LANDSCAPE_LEFT = 0;

    public int getViewWidth() {
        return mViewWidth;
    }

    public int getViewHeight() {
        return mViewHeight;
    }

    public static int getCurOriginalOrientation() {
        return curOriginalOrientation;
    }

    public PushExternalFrameFlowWindow(final Context context) {
        super(context);
        EventBus.getDefault().register(this);
        mContext = context;
        LayoutInflater.from(context).inflate(R.layout.conf_put_external_float, this);
        View view = findViewById(R.id.flow_frame_layout);
        mCameraSurface = findViewById(R.id.surface_float);
        setCameraSurfaceHolder();
        if (view.getLayoutParams() != null) {
            mViewWidth = view.getLayoutParams().width;
            mViewHeight = view.getLayoutParams().height;
        }
    }

    /**
     * 创建设备旋转监听
     */
    public void createOrientationListener() {
        mOrientationEventListener = new OrientationEventListener(mContext, SensorManager.SENSOR_DELAY_UI) {
            @Override
            public void onOrientationChanged(int i) {
                curOriginalOrientation = getOrientation(i);
                if (curOriginalOrientation > 360 || curOriginalOrientation < 0) {
                    return;
                }
            }
        };
        mOrientationEventListener.enable();
    }

    /**
     * 停止并销毁设备旋转监听
     */
    public void destroyOrientationListener() {
        EventBus.getDefault().unregister(this);
        if (mOrientationEventListener != null) {
            mOrientationEventListener.disable();
        }
        mOrientationEventListener = null;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void subscribeApplicationState(ApplicationState applicationState) {
        HCLog.i(TAG, applicationState.getState().getDescription());
        if (mCameraSurface != null) {
            mCameraSurface.setVisibility(applicationState.getState() == ApplicationState.State.BACKGROUND ? GONE : VISIBLE);
        }
    }

    /***
     * 设置SurfaceView的Holder
     */
    private void setCameraSurfaceHolder() {
        if (checkCameraHardware(mContext)) {
            mCameraSurfaceHolder.setCameraSurfaceHolder(mContext, mCameraSurface);
        }
    }

    private boolean checkCameraHardware(Context context) {
        if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
            HCLog.i(TAG, "Camera hardware is found");
            return true;
        } else {
            HCLog.e(TAG, "No camera hardware");
            return false;
        }
    }

    /**
     * 根据捕捉到的摄像头方向划分四个象限，不属于四象限则返回unknown不做处理
     * 四个象限分别是：竖向上【0-45、315-360】；横向右【45-135】；竖向下【135-225】；横向左【225-315】
     *
     * @param orientation 捕捉到的设备摄像头角度
     * @return 角度所属象限
     */
    private int getOrientation(int orientation) {
        if ((orientation < 45 && orientation >= 0) || (orientation >= 315 && orientation <= 360)) {
            return ORIENTATION_PORTRAIT_UP;
        } else if (orientation >= 45 && orientation < 135) {
            return ORIENTATION_LANDSCAPE_RIGHT;
        } else if (orientation >= 135 && orientation < 225) {
            return curOriginalOrientation;
        } else if (orientation >= 225 && orientation < 315) {
            return ORIENTATION_LANDSCAPE_LEFT;
        } else {
            return ORIENTATION_UNKNOWN;
        }
    }
}
