package com.huawei.hwscreenrecorddemo;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.AudioFormat;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RemoteViews;
import android.widget.Toast;

import com.github.faucamp.simplertmp.RtmpHandler;
import com.huawei.hwscreenrecorddemo.util.LogUtils;
import com.huawei.publishsdk.HwFlvMuxer;
import com.huawei.screenrecordsdk.screenrecord.AudioConfig;
import com.huawei.screenrecordsdk.screenrecord.ScreenRecorder;
import com.huawei.screenrecordsdk.screenrecord.VideoConfig;
import com.huawei.screenrecordsdk.util.SysUtil;

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

import static com.huawei.publishsdk.HwPublisher.H264;


public class MainActivity extends Activity implements View.OnClickListener,RtmpHandler.RtmpListener{
    private static final int REQUEST_CODE = 1;
    private MediaProjectionManager mMediaProjectionManager;
    private static ScreenRecorder mRecorder;
    private Button mButton;
    private EditText mEditText;
    private static final String TAG = "ScreenRecorder";
    private static final int STORAGE_REQUEST_CODE = 102;
    private static final int AUDIO_REQUEST_CODE   = 103;

    private boolean mPermissionGranted = false;
    private View clickedView = null;


    private HwFlvMuxer hwFlvMuxer = new HwFlvMuxer(H264,new RtmpHandler(MainActivity.this));

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.recorrd_activity_main);
        mButton = (Button) findViewById(R.id.button);
        mEditText = (EditText) findViewById(R.id.editText);

        mButton.setOnClickListener(this);
        //noinspection ResourceType
        mMediaProjectionManager = (MediaProjectionManager) getSystemService(MEDIA_PROJECTION_SERVICE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        MediaProjection mediaProjection = mMediaProjectionManager.getMediaProjection(resultCode, data);
        if (mediaProjection == null) {
            Log.e("@@", "media projection is null");
            return;
        }
        Log.e(TAG, "onActivityResult requestCode: "+requestCode );

        //获取屏幕信息
        int width = SysUtil.getScreenWidth(this);
        int height = SysUtil.getScreenHeight(this);
        int dpi = SysUtil.getScreenDpi(this);
        int api = SysUtil.getVersionCode();

        Log.e(TAG, "onActivityResult screen width : "+width +"height:"+height+"dpi"+dpi + "api:"+api);

        //音频参数配置
        AudioConfig audioConfig = new AudioConfig();
        audioConfig.ABITRATE=44100;
        audioConfig.aChannelConfig = AudioFormat.CHANNEL_IN_STEREO;
        audioConfig.ABITRATE =  64 * 1024;

        //视频参数配置
        VideoConfig videoConfig = new VideoConfig();
        videoConfig.mGop =15;
        videoConfig.mBitRate =500000;
        videoConfig.mDpi =dpi;
        videoConfig.mFrameRate =15;
        videoConfig.mHeight = height;
        videoConfig.mWidth = width;

        //开始录制
        mRecorder = new ScreenRecorder(this,audioConfig, videoConfig, mediaProjection,hwFlvMuxer);
        mRecorder.start();

        //开始打包flV，并且推流
        String url = mEditText.getText().toString();
        Log.e(TAG, "onActivityResult url: " +url );
        hwFlvMuxer.start(url);


        mButton.setText("Stop Recorder");
        Toast.makeText(this, "Screen recorder is running...", Toast.LENGTH_SHORT).show();
        moveTaskToBack(true);
    }

    @Override
    public void onBackPressed() {
        if (mRecorder !=null){
            moveTaskToBack(true);
        }else {
            super.onBackPressed();
        }
    }

    private void stopRecorder(){
        //停止消息栏通知服务
        Intent intentNotification = new Intent(this, NotificationService.class);
        this.stopService(intentNotification);

        if (mRecorder != null){
            mRecorder.quit();
            mRecorder = null;
            mButton.setText("Restart recorder");
        }

    }

    @Override
    public void onClick(View v) {
        if(!mPermissionGranted){//没有权限，则请求权限
            clickedView = v;
            checkAllPermission();
            return;
        }
        if (mRecorder != null) {
            
            stopRecorder();
        } else {
            //开始消息栏通知服务，此处解决Android 9.0，后台录音最多只能录制一分钟限制。
            Intent intentNotification = new Intent(this, NotificationService.class);
            this.startService(intentNotification);

            //录屏系统服务
            Intent captureIntent = mMediaProjectionManager.createScreenCaptureIntent();
            startActivityForResult(captureIntent, REQUEST_CODE);
        }
    }

    private void checkAllPermission() {
        //获取录音和写文件权限
        if (PackageManager.PERMISSION_GRANTED == ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            if (PackageManager.PERMISSION_GRANTED == ContextCompat.checkSelfPermission(this, android.Manifest.permission.RECORD_AUDIO)) {
                mPermissionGranted = true;
                onClick(clickedView);
            } else {
                ActivityCompat.requestPermissions(this,
                        new String[] {Manifest.permission.RECORD_AUDIO}, AUDIO_REQUEST_CODE);
            }
        } else {
            ActivityCompat.requestPermissions(this,
                    new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, STORAGE_REQUEST_CODE);
        }
    }



    @Override
    protected void onDestroy() {
        //销毁录屏
        super.onDestroy();
        if(mRecorder != null){
            mRecorder.quit();
            mRecorder = null;
        }
    }

    /**
     * 后面这些为rtmp回调事件，如连接成功，断开连接，异常回调等。
     * @param s
     */
    @Override
    public void onRtmpConnecting(String s) {

    }

    @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() {
        Log.e(TAG, "onRtmpDisconnected: " );
    }

    @Override
    public void onRtmpVideoFpsChanged(double v) {

    }

    @Override
    public void onRtmpVideoBitrateChanged(double v) {

    }

    @Override
    public void onRtmpAudioBitrateChanged(double v) {

    }

    @Override
    public void onRtmpSocketException(SocketException e) {

    }

    @Override
    public void onRtmpIOException(IOException e) {

    }

    @Override
    public void onRtmpIllegalArgumentException(IllegalArgumentException e) {

    }

    @Override
    public void onRtmpIllegalStateException(IllegalStateException e) {

    }

    private final String RECORDER_STOP = "stop";
    private final String RECORDER_PAUSE = "pause";
    private final String RECORDER_RESUME = "resume";
    private final String RECORDER_HOME = "come_home";
    //通知的唯一标识号。
    private int NOTIFICATION = R.string.notification_live_start;


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

        if (mRecorder == null){
            LogUtils.d("mRecorder == null");
        }else {
            LogUtils.d("mRecorder != null");
            LogUtils.d("mRecorder.getState().toString(): "+mRecorder.getState().toString());
        }
        String extra = getIntent().getStringExtra("flag");
        LogUtils.d("extra :"+extra);
        if (!TextUtils.isEmpty(extra) && mRecorder != null){
            LogUtils.d("onNewIntent");
            switch (extra){
//                case RECORDER_STOP:
//                    LogUtils.d("RECORDER_STOP");
//                    stopRecorder();
//                    break;
                case RECORDER_PAUSE:
                    LogUtils.d("RECORDER_PAUSE");
                    mRecorder.pauseVideo();
                    NotificationService.getNotification().contentView.setViewVisibility(R.id.pause,View.GONE);
                    NotificationService.getNotification().contentView.setViewVisibility(R.id.resume,View.VISIBLE);
                    NotificationService.getNotificationManager().notify(NOTIFICATION,NotificationService.getNotification());
                    break;
                case RECORDER_RESUME:
                    LogUtils.d("RECORDER_RESUME");
                    NotificationService.getNotification().contentView.setViewVisibility(R.id.pause,View.VISIBLE);
                    NotificationService.getNotification().contentView.setViewVisibility(R.id.resume,View.GONE);
                    NotificationService.getNotificationManager().notify(NOTIFICATION,NotificationService.getNotification());
                    mRecorder.resumeVideo();
                    break;
                case RECORDER_HOME:
//                    Intent intentHome = new Intent();
//                    // 为Intent设置Action、Category属性
//                    intentHome.setAction(Intent.ACTION_MAIN);// "android.intent.action.MAIN"
//                    intentHome.addCategory(Intent.CATEGORY_HOME); //"android.intent.category.HOME"
//                    startActivity(intentHome);
                    LogUtils.d("RECORDER_HOME");
                    break;
            }

        }

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        setIntent(intent);

    }
}
