package com.huawei.pushpuresdkdemo;

import android.annotation.SuppressLint;
import android.content.res.Configuration;
import android.graphics.Point;
import android.hardware.Camera;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Toast;

import com.github.faucamp.simplertmp.RtmpHandler;
import com.huawei.publishsdk.HWCameraSurfaceView;
import com.huawei.publishsdk.HWVideoFrame;
import com.huawei.publishsdk.HwEncodeHandler;
import com.huawei.publishsdk.HwPublisher;
import com.huawei.publishsdk.HwRecordHandler;

import java.io.IOException;
import java.net.SocketException;

import static com.huawei.publishsdk.HwPublisher.ARGB;
import static com.huawei.publishsdk.HwPublisher.NV21;

public class MainActivity2 extends AppCompatActivity implements HwEncodeHandler.HwEncodeListener, RtmpHandler.RtmpListener, HwRecordHandler.HwRecordListener {
    private static final String TAG = "MainActivity2";
    private static final int ZOOM_OUT = 0;
    private static final int ZOOM_IN = 1;
    private static final int ZOOM_DELTA = 1;
    private String rtmpUrl = "rtmp://kitpush.hwcloudlive.com/live1/sdkdemo3";
    private HWCameraSurfaceView mCameraView;
    private HwPublisher mPublisher;

    private Button btnPublish;
    private Button btnSwitchCamera;

    private FocusImageView mFocusImageView;
    private ScaleGestureDetector mScaleDetector;
    private int mScaleFactor = 1;
    public boolean mIsFocus;

    @SuppressLint("WrongViewCast")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.activity_main2);

        btnPublish = (Button) findViewById(R.id.publish);
        btnSwitchCamera = (Button) findViewById(R.id.swCam);
        mCameraView = (HWCameraSurfaceView) findViewById(R.id.glsurfaceview_camera2);
        mFocusImageView = (FocusImageView) findViewById(R.id.focusImageView);

        //这里回调根据需要使用，不需要摄像头数据回调时，可以设置为null
        mPublisher = new HwPublisher(this, mCameraView, new HwPublisher.HwPreviewCallback() {
            @Override
            public void onGetHwVideoFrame(HWVideoFrame hwVideoFrame) {
                //回调摄像头采集原始数据，格式 NV21
//                mPublisher.pushExternVideoFrame(hwVideoFrame);
            }
        }, false);
        mPublisher.setEncodeHandler(new HwEncodeHandler(this));
        mPublisher.setRtmpHandler(new RtmpHandler(this));
        mPublisher.setRecordHandler(new HwRecordHandler(this));

        mPublisher.setOutputResolution(720, 1280);
        mPublisher.setVideoHDMode();
        mPublisher.setVfps(15);
        mPublisher.setStatisticEnable(true);
//        mPublisher.switchToSoftEncoder();

        mCameraView.setAutoFocusCallback(autoFocusCallback);
        mScaleDetector = new ScaleGestureDetector(this, new ScaleListener());

        btnPublish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (btnPublish.getText().toString().contentEquals("publish")) {
                    mPublisher.startAudioRecord();
                    mPublisher.startPublish(rtmpUrl);
                    btnPublish.setText("stop");
                } else if (btnPublish.getText().toString().contentEquals("stop")) {
                    mPublisher.stopAudioRecord();
                    mPublisher.stopPublish();
                    btnPublish.setText("publish");
                }
            }
        });

        btnSwitchCamera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPublisher.switchCameraFace((mPublisher.getCamraId() + 1) % Camera.getNumberOfCameras());
            }
        });


    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if(mScaleDetector!=null){
            Log.e(TAG, "dispatchTouchEvent mScaleDetector is not null! ");
            mScaleDetector.onTouchEvent(event);
        }

        switch (event.getAction()& MotionEvent.ACTION_MASK) {
            case MotionEvent.ACTION_DOWN:
                Log.e(TAG, "dispatchTouchEvent ACTION_DOWN! ");
                mIsFocus = true;
                break;
            case MotionEvent.ACTION_UP:
                Point pointFocus =new Point((int)event.getX(),(int)event.getY());
                Log.e(TAG, "dispatchTouchEvent ACTION_UP! ");
                if (mIsFocus) {
                    mFocusImageView.startFocus(pointFocus);
                    if ( mPublisher != null) {
                        mPublisher.setFocus( pointFocus);
                    }
                }
                break;
            case MotionEvent.ACTION_POINTER_DOWN:
                Log.e(TAG, "dispatchTouchEvent ACTION_POINTER_DOWN! ");
                mIsFocus = false;
                break;
        }
        return super.onTouchEvent(event);
    }

    private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {

        @Override
        public boolean onScale(ScaleGestureDetector detector) {
            mScaleFactor = (int) detector.getScaleFactor();
            if (mPublisher != null) {
                setZoom();
            }
            return true;
        }
    }

    private void setZoom() {
        int zoom = mPublisher.getZoom();
        if (mScaleFactor == ZOOM_IN) {
            if (zoom < mPublisher.getMaxZoom()) zoom += ZOOM_DELTA;
        } else if (mScaleFactor == ZOOM_OUT) {
            if (zoom > 0) zoom -= ZOOM_DELTA;
        }
        mPublisher.setZoom(zoom);
    }

    private final Camera.AutoFocusCallback autoFocusCallback = new Camera.AutoFocusCallback() {
        @Override
        public void onAutoFocus(boolean success, Camera camera) {
            //聚焦之后根据结果修改图片
            if (success) {
                Log.e(TAG, "onAutoFocus  success!! " );
                mFocusImageView.onFocusSuccess();
            } else {
                //聚焦失败显示的图片，由于未找到合适的资源，这里仍显示同一张图片
                Log.e(TAG, "onAutoFocus  failed!! " );
                mFocusImageView.onFocusFailed();
            }
        }
    };

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        mPublisher.stopPublish();
        mPublisher.stopRecord();
        mPublisher.setScreenOrientation(newConfig.orientation);
        if (btnPublish.getText().toString().contentEquals("stop")) {
            mPublisher.startPublish(rtmpUrl);
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
    }
    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mPublisher.stopPublish();
        mPublisher.stopRecord();
        mPublisher.stopAudioRecord();
        mPublisher.stopCamera();
        mPublisher.release();
    }


    @Override
    public void onNetworkWeak() {

    }

    @Override
    public void onNetworkResume() {

    }

    @Override
    public void onEncodeIllegalArgumentException(IllegalArgumentException e) {
        Log.e(TAG, "onEncodeIllegalArgumentException: "+e );
    }

    @Override
    public void onRtmpConnecting(String msg) {

    }

    @Override
    public void onRtmpConnected(String msg) {
        Log.e(TAG, "onRtmpConnected: " );
    }

    @Override
    public void onRtmpVideoStreaming() {

    }

    @Override
    public void onRtmpAudioStreaming() {

    }

    @Override
    public void onRtmpStopped() {

    }

    @Override
    public void onRtmpDisconnected() {

    }

    @Override
    public void onRtmpVideoFpsChanged(double fps) {

    }

    @Override
    public void onRtmpVideoBitrateChanged(double bitrate) {

    }

    @Override
    public void onRtmpAudioBitrateChanged(double bitrate) {

    }

    @Override
    public void onRtmpSocketException(SocketException e) {
        handleException(e);
    }

    @Override
    public void onRtmpIOException(IOException e) {
        handleException(e);
    }

    @Override
    public void onRtmpIllegalArgumentException(IllegalArgumentException e) {
        handleException(e);
    }

    @Override
    public void onRtmpIllegalStateException(IllegalStateException e) {
        handleException(e);
    }

    @Override
    public void onRecordPause() {

    }

    @Override
    public void onRecordResume() {

    }

    @Override
    public void onRecordStarted(String msg) {

    }

    @Override
    public void onRecordFinished(String msg) {

    }

    @Override
    public void onRecordIllegalArgumentException(IllegalArgumentException e) {

    }

    @Override
    public void onRecordIOException(IOException e) {

    }

    private void handleException(Exception e) {
        try {
            Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
            mPublisher.stopPublish();
            mPublisher.stopRecord();

            btnPublish.setText("publish");
        } catch (Exception e1) {
            //
        }
    }
}
