package com.huawei.hwmdemo.externalframe;

import android.app.Activity;
import android.content.Context;
import android.hardware.Camera;
import android.view.SurfaceHolder;

import com.huawei.hwmlogger.HCLog;

/**
 * 相机界面SurfaceView的回调类
 */
public final class SurfaceViewCallback implements SurfaceHolder.Callback, Camera.PreviewCallback {

    static final String TAG = SurfaceViewCallback.class.getSimpleName();
    Context context;
    FrontCamera mFrontCamera = new FrontCamera();
    boolean previewing = mFrontCamera.getPreviewing();
    Camera mCamera;
    FaceTask mFaceTask;
    Camera.Parameters parameters;

    public void setContext(Context context) {
        this.context = context;
    }

    @Override
    public void surfaceCreated(SurfaceHolder surfaceHolder) {
        //初始化摄像头
        mFrontCamera.setCamera(mCamera);
        mCamera = mFrontCamera.initCamera();
        if (mCamera != null) {
            parameters = mCamera.getParameters();
            if (parameters == null) {
                HCLog.e(TAG, " parameters is null. ");
                return;
            }
            mCamera.setPreviewCallback(this);
            //适配竖排固定角度
            FrontCamera.setCameraDisplayOrientation((Activity) context, mFrontCamera.getCurrentCamIndex(), mCamera);
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
        HCLog.i(TAG, "surfaceChanged");
        if (previewing) {
            mCamera.stopPreview();
            HCLog.i(TAG, "stopPreview");
        }

        try {
            mCamera.setPreviewDisplay(surfaceHolder);
            mCamera.startPreview();
            mCamera.setPreviewCallback(this);
        } catch (Exception e) {
            HCLog.e(TAG, e.getMessage());
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
        mFrontCamera.stopCamera(mCamera);
        HCLog.i(TAG, "surfaceDestroyed");
    }

    /**
     * 相机实时数据的回调
     *
     * @param data   相机获取的数据，格式是YUV
     * @param camera 相应相机的对象
     */
    @Override
    public void onPreviewFrame(byte[] data, Camera camera) {
        if (mFaceTask != null) {
            switch (mFaceTask.getStatus()) {
                case RUNNING:
                    return;
                case PENDING:
                    mFaceTask.cancel(false);
                    break;
                default:
                    break;
            }
        }
        if (data != null && parameters != null) {
            mFaceTask = new FaceTask(data, parameters);
            mFaceTask.execute((Void) null);
        }
    }
}