package com.mogo.cloud;

import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.TextureView;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.ToggleButton;

import androidx.appcompat.app.AppCompatActivity;

import com.mogo.cloud.util.YuvToolUtils;
import com.zhidao.manager.camera.FrameBufferCallBack;
import com.zhidao.manager.camera.ZDCameraManager;
import com.zhidao.manager.camera.ZDCameraParams;


public abstract class BaseLiveActivity extends AppCompatActivity {
    private String TAG = "TestCarRecorderLiveActivity";

    private String yuvSavePath = "/sdcard/Movies/TestYuvNV12.yuv";

    public static int cameraId = 0;  // 要打开的摄像头的ID

    public int videoWidth = 1280;
    public int videoHeight = 720;

    // 开始直播
    protected ToggleButton btnLive;
    // 保存文件到本地
    protected ToggleButton btnSaveFile;
    // 设置摄像头与状态
    protected ToggleButton btnChangeCameraState;
    // 当前直播的状态
    protected TextView tvLiveStatus;
    // 相机数据预览
    protected SurfaceView surfacePreviewView;

    // 查看指定车机的画面
    protected TextureView textureView;
    // 查看直播按钮
    protected ToggleButton liveToggleBtn;
    // 登录第二个房间的按钮
    protected ToggleButton tbLoginMultiRoom;
    // 要查看的车机SN
    protected EditText etLookRoomId;
    // WIFI状态
    protected TextView tvWifiState;

    private ZDCameraManager zdCameraManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_live_play_and_push);

        surfacePreviewView = findViewById(R.id.surfacePreviewView);
        btnLive = findViewById(R.id.btnLive);
        btnLive.setOnCheckedChangeListener((buttonView, isChecked) -> {
//            Toast.makeText(getApplicationContext(), buttonView.getText(), Toast.LENGTH_SHORT).show();
            toggleLive(isChecked);
        });

        btnSaveFile = findViewById(R.id.btnSaveFile);
        btnSaveFile.setOnCheckedChangeListener((btnSaveFile, isChecked) -> {
//            Toast.makeText(getApplicationContext(), btnSaveFile.getText(), Toast.LENGTH_SHORT).show();
            YuvToolUtils.isSaveFile = isChecked;
            if (isChecked) {
                YuvToolUtils.connectYUVFile(yuvSavePath);
            }
        });

        btnChangeCameraState = findViewById(R.id.btnChangeCameraState);
        btnChangeCameraState.setOnCheckedChangeListener((btnSaveFile, isChecked) -> {
//            Toast.makeText(getApplicationContext(), btnSaveFile.getText(), Toast.LENGTH_SHORT).show();
            toggleCameraState(isChecked);
        });

        tvLiveStatus = findViewById(R.id.tvLiveStatus);

        textureView = findViewById(R.id.textureView);
        etLookRoomId = findViewById(R.id.etLookRoomId);
        liveToggleBtn = findViewById(R.id.liveToggleBtn);
        liveToggleBtn.setOnCheckedChangeListener((buttonView, isChecked) -> {
//            Toast.makeText(getApplicationContext(), buttonView.getText(), Toast.LENGTH_SHORT).show();
            togglePlay(isChecked);
        });


        tbLoginMultiRoom = findViewById(R.id.tbLoginMultiRoom);
        tbLoginMultiRoom.setOnCheckedChangeListener((buttonView, isChecked) -> {
//            Toast.makeText(getApplicationContext(), buttonView.getText(), Toast.LENGTH_SHORT).show();
            toggleLoginMultiRoom(isChecked);
        });
        tvWifiState = findViewById(R.id.tvWifiState);

        initCamer();
    }

    /**
     * 初始化相机
     */
    private void initCamer() {
        zdCameraManager = ZDCameraManager.getInstance();
        zdCameraManager.init(getApplicationContext());
        ZDCameraParams camParam = zdCameraManager.getCameraParam();
        camParam.setStoragePath("/sdcard/DCIM/");
        camParam.setVideoWidth(0, videoWidth);
        camParam.setVideoHeight(0, videoHeight);
        zdCameraManager.setCameraParam(camParam);

        // 这里是获取 YUV-NV12 格式的视频流
        ZDCameraManager.getInstance().setFrontBufferCallBack(new FrameBufferCallBack() {
            @Override
            public void onFrame(byte[] bytes, int i) {
                //Log.d(TAG, "duanmu OnFrame ,bytes:" + bytes + " i:" + i);
                // 回碉给业务侧进行处理
                // 这里对所有传入的YUV数据进行对应类型的转码，为I420
                byte[] yuv420p = YuvToolUtils.convertData(bytes, videoWidth, videoHeight, 4);

                onVideoFrame(yuv420p, i);

                // 保存yuv文件
                if (YuvToolUtils.isSaveFile) {
                    try {
                        // 往队列里面添加数据
                        YuvToolUtils.queueYUV.put(yuv420p);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

        // 这里是纯预览
        surfacePreviewView.getHolder().addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                Log.i(TAG, "addSurfaceCallBack id");
                zdCameraManager.startPreview(holder, cameraId, videoWidth, videoHeight);
            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
            }

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
                zdCameraManager.stopPreview(cameraId);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (zdCameraManager != null) {
            zdCameraManager.stopPreview(cameraId);
        }
    }

    /**
     * F 车机从相机获取的视频数据回调
     * <p>
     * TODO 一般在这里调用直播SDK的接口进行直播操作，一定要先卸载 ADAS com.zhidao.autopilot
     *
     * @param yuv420p     YUV数据 I420
     * @param bytesLength 数据长度
     */
    public abstract void onVideoFrame(byte[] yuv420p, int bytesLength);


    /**
     * 开关直播状态
     *
     * @param isLive true-开启直播，false-关闭直播
     */
    public abstract void toggleLive(boolean isLive);

    /**
     * 摄像头状态
     *
     * @param isLive true-可以直播，false-不可以直播
     */
    public abstract void toggleCameraState(boolean isLive);

    /**
     * 开关查看直播
     *
     * @param isPlay true-查看直播，false-不查看直播
     */
    public abstract void togglePlay(boolean isPlay);

    /**
     * 登录或退出第二个房间
     *
     * @param isLogin true-登录，false-退出
     */
    public abstract void toggleLoginMultiRoom(boolean isLogin);

}