package com.huawei.pushpuresdkdemo;

import android.annotation.SuppressLint;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Point;
import android.hardware.Camera;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
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.EditText;
import android.widget.SeekBar;
import android.widget.Toast;

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

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

public class MainActivity extends AppCompatActivity implements RtmpHandler.RtmpListener,
        HwRecordHandler.HwRecordListener, HwEncodeHandler.HwEncodeListener  {

    private static final String TAG = "MainActivity";
    private static final int ZOOM_OUT = 0;
    private static final int ZOOM_IN = 1;
    private static final int ZOOM_DELTA = 1;

    private Button btnPublish;
    private Button btnSwitchCamera;
    private Button btnRecord;
    private Button btnSwitchEncoder;
    private Button btnMediaType;

    private SharedPreferences sp;
    private String rtmpUrl = "rtmp://kitpush.hwcloudlive.com/live1/sdkdemo";
//    private String rtmpUrl = "rtmp://newlive.house365.com/live/24486";
    private String recPath = Environment.getExternalStorageDirectory().getPath() + "/puretest.mp4";

    private HwPublisher mPublisher;
    private HwCameraView mCameraView;
    private SeekBar sbZoom;
    private FocusImageView mFocusImageView;
    private ScaleGestureDetector mScaleDetector;
    private int mScaleFactor = 1;
    public boolean mIsFocus;

    HwPublisher.HwPreviewCallback cb = new HwPublisher.HwPreviewCallback() {
        @Override
        public void onGetHwVideoFrame(HWVideoFrame hwVideoFrame) {
            //回调摄像头采集视频数据，格式RGBA
        }
    };

    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        // response screen rotation event
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR);

        // restore data.
        sp = getSharedPreferences("huawei", MODE_PRIVATE);
        rtmpUrl = sp.getString("rtmpUrl", rtmpUrl);

        // initialize url.
        final EditText efu = (EditText) findViewById(R.id.url);
        efu.setText(rtmpUrl);

        btnPublish = (Button) findViewById(R.id.publish);
        btnSwitchCamera = (Button) findViewById(R.id.swCam);
        btnRecord = (Button) findViewById(R.id.record);
        btnSwitchEncoder = (Button) findViewById(R.id.swEnc);
        btnMediaType = (Button) findViewById(R.id.MediaType);
        mCameraView = (HwCameraView) findViewById(R.id.glsurfaceview_camera);
        sbZoom = (SeekBar) findViewById(R.id.sb_zoom);
        mFocusImageView = (FocusImageView) findViewById(R.id.focusImageView);

        mPublisher = new HwPublisher(this, mCameraView,null,false);
        mPublisher.setEncodeHandler(new HwEncodeHandler(this),"video/avc");
        mPublisher.setRtmpHandler(new RtmpHandler(this),"video/avc");
        mPublisher.setRecordHandler(new HwRecordHandler(this));
        mPublisher.setPreviewResolution(1280, 720);//19201080
        mPublisher.setOutputResolution(720, 1280);
        mPublisher.setVideoHDMode();
//        mPublisher.switchCameraFace(1);
        mPublisher.setVfps(15);
        mPublisher.startCamera();
        mPublisher.startAudioRecord();
        mPublisher.setStatisticEnable(true);

        //需要原始数据回调时设置
//        mPublisher.setHwPreviewVideoCallback(cb);

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

        sbZoom.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                Log.e(TAG, "当前进度值:" + progress + "  / 100 ");
//                mPublisher.setFocusMode(FOCUS_MODE_AUTO);
                if((mPublisher!=null)&&(mPublisher.isSupportZoom())&&(progress<mPublisher.getMaxZoom())){
                    mPublisher.setZoom(progress);
                    mPublisher.startAutoFocus();
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                Log.e(TAG, "触碰SeekBar:");
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                Log.e(TAG, "放开SeekBar:");
            }
        });

        btnPublish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (btnPublish.getText().toString().contentEquals("publish")) {
                    rtmpUrl = efu.getText().toString();
                    SharedPreferences.Editor editor = sp.edit();
                    editor.putString("rtmpUrl", rtmpUrl);
                    editor.apply();

                    mPublisher.startPublish(rtmpUrl);

                    btnPublish.setText("stop");
                    btnSwitchEncoder.setEnabled(false);
                } else if (btnPublish.getText().toString().contentEquals("stop")) {
                    mPublisher.stopPublish();
                    mPublisher.stopRecord();
                    btnPublish.setText("publish");
                    btnRecord.setText("record");
                    btnSwitchEncoder.setEnabled(true);
                }
            }
        });
        btnMediaType.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(btnMediaType.getText().toString().equals("AUDIO+VIDEO")){
                    mPublisher.setSendType(HwPublisher.sendAudioOnly);
                    mPublisher.stopCamera();
                    btnMediaType.setText("AUDIO");
                }else if(btnMediaType.getText().toString().equals("AUDIO")){
                    mPublisher.setSendType(HwPublisher.sendVideoOnly);
                    mPublisher.startCamera();
                    btnMediaType.setText("VIDEO");
                }
                else{
                    mPublisher.setSendType(HwPublisher.sendAudioVideoBoth);
                    mPublisher.startCamera();
                    btnMediaType.setText("AUDIO+VIDEO");
                }
            }
        });

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

        btnRecord.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (btnRecord.getText().toString().contentEquals("record")) {
                    if (mPublisher.startRecord(recPath)) {
                        btnRecord.setText("pause");
                    }
                } else if (btnRecord.getText().toString().contentEquals("pause")) {
                    mPublisher.pauseRecord();
                    btnRecord.setText("resume");
                } else if (btnRecord.getText().toString().contentEquals("resume")) {
                    mPublisher.resumeRecord();
                    btnRecord.setText("pause");
                }
            }
        });

        btnSwitchEncoder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (btnSwitchEncoder.getText().toString().contentEquals("soft encoder")) {
                    mPublisher.switchToSoftEncoder();
                    btnSwitchEncoder.setText("hard encoder");
                } else if (btnSwitchEncoder.getText().toString().contentEquals("hard encoder")) {
                    mPublisher.switchToHardEncoder();
                    btnSwitchEncoder.setText("soft encoder");
                }
            }
        });
    }

    @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
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onResume() {
        super.onResume();
//        final Button btn = (Button) findViewById(R.id.publish);
//        btn.setEnabled(true);
        if(btnRecord.getText().toString().contentEquals("resume")){
            mPublisher.resumeRecord();
            btnRecord.setText("pause");
        }
        mPublisher.startCamera();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if(btnRecord.getText().toString().contentEquals("pause")){
            mPublisher.pauseRecord();
            btnRecord.setText("resume");
        }
        mPublisher.stopCamera();
    }

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

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        mPublisher.stopPublish();
        mPublisher.stopRecord();
        btnRecord.setText("record");
        Log.e(TAG, "onConfigurationChanged: "+newConfig.orientation );
        mPublisher.setScreenOrientation(newConfig.orientation);
        if (btnPublish.getText().toString().contentEquals("stop")) {
            mPublisher.startPublish(rtmpUrl);
        }
        mPublisher.startCamera();
    }

    private void handleException(Exception e) {
        try {
            Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
            mPublisher.stopPublish();
            mPublisher.stopRecord();
            btnPublish.setText("publish");
            btnRecord.setText("record");
            btnSwitchEncoder.setEnabled(true);
        } catch (Exception e1) {
            //
        }
    }

    @Override
    public void onRtmpConnecting(String msg) {
        Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onRtmpConnected(String msg) {
        Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onRtmpVideoStreaming() {
    }

    @Override
    public void onRtmpAudioStreaming() {
    }

    @Override
    public void onRtmpStopped() {
        Toast.makeText(getApplicationContext(), "Stopped", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onRtmpDisconnected() {
        Toast.makeText(getApplicationContext(), "Disconnected", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onRtmpVideoFpsChanged(double fps) {
        Log.i(TAG, String.format("Output Fps: %f", fps));
    }

    @Override
    public void onRtmpVideoBitrateChanged(double bitrate) {
        int rate = (int) bitrate;
        if (rate / 1000 > 0) {
            Log.i(TAG, String.format("Video bitrate: %f kbps", bitrate / 1000));
        } else {
            Log.i(TAG, String.format("Video bitrate: %d bps", rate));
        }
    }

    @Override
    public void onRtmpAudioBitrateChanged(double bitrate) {
        int rate = (int) bitrate;
        if (rate / 1000 > 0) {
            Log.i(TAG, String.format("Audio bitrate: %f kbps", bitrate / 1000));
        } else {
            Log.i(TAG, String.format("Audio bitrate: %d bps", rate));
        }
    }

    @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);
    }

    // Implementation of SrsRecordHandler.

    @Override
    public void onRecordPause() {
        Toast.makeText(getApplicationContext(), "Record paused", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onRecordResume() {
        Toast.makeText(getApplicationContext(), "Record resumed", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onRecordStarted(String msg) {
        Toast.makeText(getApplicationContext(), "Recording file: " + msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onRecordFinished(String msg) {
        Toast.makeText(getApplicationContext(), "MP4 file saved: " + msg, Toast.LENGTH_SHORT).show();
    }

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

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

    // Implementation of SrsEncodeHandler.

    @Override
    public void onNetworkWeak() {
        Toast.makeText(getApplicationContext(), "Network weak", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onNetworkResume() {
        Toast.makeText(getApplicationContext(), "Network resume", Toast.LENGTH_SHORT).show();
    }

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