package com.tencent.gme.audio.apiexample;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.ActionBar;

import com.gme.TMG.ITMGContext;
import com.gme.TMG.ITMGType;

public class VoiceMessageRecognitionActivity extends BaseActivity implements
        TMGDispatcherBase,
        View.OnClickListener {
    private ScrollView mLogHostView;
    private TextView mLogMonitorView;
    private EditText mRecFilePathView;
    private EditText mRecFileUrlView;
    private EditText mDownloadFileView;
    private EditText mRecognizeTextView;
    private CheckBox mRealTimeStreamFlagView;
    private int mFileIndex = 1;
    private boolean mIsRecording = false;
    private boolean mIsPlaying = false;

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

        initActionBar("Voice Message & Recognition");

        initViews();

        byte[] authBuffer = GMEAuthBufferHelper.getInstance().createAuthBuffer("");
        // Step 1/12 apply ptt authbuffer
        // https://cloud.tencent.com/document/product/607/56341#.E9.89.B4.E6.9D.83.E4.BF.A1.E6.81.AF

        ITMGContext.GetInstance(this).GetPTT().ApplyPTTAuthbuffer(authBuffer);
        TMGCallbackDispatcher.getInstance().registerSubDispatcher(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        TMGCallbackDispatcher.getInstance().unregisterSubDispatcher(this);
    }

    private void initViews() {
        findViewById(R.id.ll_root).setOnClickListener(this);
        findViewById(R.id.btnStartRec).setOnClickListener(this);
        findViewById(R.id.btnCancelRec).setOnClickListener(this);
        findViewById(R.id.btnStopRec).setOnClickListener(this);
        findViewById(R.id.btnPreviewRec).setOnClickListener(this);
        findViewById(R.id.btnUpload).setOnClickListener(this);
        findViewById(R.id.btnDownload).setOnClickListener(this);
        findViewById(R.id.btnPlay).setOnClickListener(this);
        findViewById(R.id.btnRecognize).setOnClickListener(this);
        findViewById(R.id.btnClear).setOnClickListener(this);

        mLogMonitorView = findViewById(R.id.tv_Monitor);
        mLogHostView = findViewById(R.id.sv_host);
        mRecFilePathView = findViewById(R.id.etRecFilePath);
        mRecFileUrlView = findViewById(R.id.etRecFileUrl);
        mDownloadFileView = findViewById(R.id.etRecDownloadFile);
        mRecognizeTextView = findViewById(R.id.etRecognizeText);
        mRealTimeStreamFlagView = findViewById(R.id.cbRealTimeStream);
    }

    @Override
    public void onClick(View v) {
        final int id = v.getId();
        if (id == R.id.btnStartRec) {
            onStartRecClick();
        } else if (id == R.id.btnCancelRec) {
            onCancelRecClick();
        } else if (id == R.id.btnStopRec) {
            onStopRecClick();
        } else if (id == R.id.btnUpload) {
            onUploadClick();
        } else if (id == R.id.btnPreviewRec) {
            onPreviewRecClick();
        } else if (id == R.id.btnDownload) {
            onDownloadRecClick();
        } else if (id == R.id.btnPlay) {
            onPlayDownloadFileClick();
        } else if (id == R.id.btnRecognize) {
            onRecognizeClick();
        } else if (id == R.id.btnClear) {
            mLogMonitorView.setText("");
            mRecFilePathView.setText("");
            mRecFileUrlView.setText("");
            mDownloadFileView.setText("");
            mRecognizeTextView.setText("");
        }
    }

    private void onStartRecClick() {
        if (mIsRecording) {
            appendLog2MonitorView("is Recording, please start later");
            return;
        }
        mIsRecording = true;

        mRecFilePathView.setText("");
        mRecFileUrlView.setText("");
        mDownloadFileView.setText("");
        mRecognizeTextView.setText("");

        appendLog2MonitorView("Start Recording");
        String recordfilePath = getExternalFilesDir(null).getAbsolutePath() + "/test_" + (mFileIndex++) + ".ogg";

        if (mRealTimeStreamFlagView.isChecked()) // 实时语音识别
        {
            // step 1.1/3 start recording and real time recognition, need handle ITMG_MAIN_EVENT_TYPE_PTT_STREAMINGRECOGNITION_IS_RUNNING and HandleSTREAM2TEXTComplete event
            // https://cloud.tencent.com/document/product/607/56341#.3Ca-id.3D.22startrwsr.22.3E.E5.90.AF.E5.8A.A8.E6.B5.81.E5.BC.8F.E8.AF.AD.E9.9F.B3.E8.AF.86.E5.88.AB.3C.2Fa.3E
            ITMGContext.GetInstance(this).GetPTT().StartRecordingWithStreamingRecognition(recordfilePath, "cmn-Hans-CN");
        } else {
            // Step 2/12 start recording
            // https://cloud.tencent.com/document/product/607/56341#.E5.90.AF.E5.8A.A8.E5.BD.95.E9.9F.B3
            ITMGContext.GetInstance(this).GetPTT().StartRecording(recordfilePath);
        }
    }

    private void onCancelRecClick() {
        mIsRecording = false;
        appendLog2MonitorView("Cancel Record");
        mRecFilePathView.setText(String.format(""));
        // 取消录音，这个操作不会有任何回调
        // https://cloud.tencent.com/document/product/607/56341#.E5.8F.96.E6.B6.88.E5.BD.95.E9.9F.B3
        ITMGContext.GetInstance(this).GetPTT().CancelRecording();
    }

    private void onStopRecClick() {
        mIsRecording = true;
        appendLog2MonitorView("Stop Record");
        mRecFilePathView.setText(String.format(""));

        // Step 3/12 stop recording,  need handle ITMG_MAIN_EVENT_TYPE_PTT_RECORD_COMPLETE event
        // https://cloud.tencent.com/document/product/607/56341#.3Ca-id.3D.22stop.22.3E.E5.81.9C.E6.AD.A2.E5.BD.95.E9.9F.B3.3C.2Fa.3E
        ITMGContext.GetInstance(this).GetPTT().StopRecording();
    }

    private void onPreviewRecClick() {
        if (mIsPlaying) {
            return;
        }
        mIsPlaying = true;
        appendLog2MonitorView("Preview record file");
        String recordFilePath = mRecFilePathView.getText().toString().trim();

        // 播放录制的语音，会有类型为 ITMG_MAIN_EVENT_TYPE_PTT_PLAY_COMPLETE 的回调事件
        // https://cloud.tencent.com/document/product/607/56341#.E6.92.AD.E6.94.BE.E8.AF.AD.E9.9F.B3
        ITMGContext.GetInstance(this).GetPTT().PlayRecordedFile(recordFilePath);
    }

    private void onUploadClick() {
        String recordFilePath = mRecFilePathView.getText().toString().trim();
        if (TextUtils.isEmpty(recordFilePath)) {
            appendLog2MonitorView("Record file path is empty");
            return;
        }
        appendLog2MonitorView("Start upload record file");
        // Step 5/12 upload voice file to server, need handle ITMG_MAIN_EVENT_TYPE_PTT_UPLOAD_COMPLETE event
        // https://cloud.tencent.com/document/product/607/56341#.E4.B8.8A.E4.BC.A0.E8.AF.AD.E9.9F.B3.E6.96.87.E4.BB.B6
        ITMGContext.GetInstance(this).GetPTT().UploadRecordedFile(recordFilePath);
    }

    private void onDownloadRecClick() {
        String templedownload = getExternalFilesDir(null).getAbsolutePath() + "/downLoad_" + (mFileIndex++) + ".ogg";
        String _downloadurl = mRecFileUrlView.getText().toString();

        appendLog2MonitorView("Start download record file");
        // Step 7/12 download vocie file from server, need handle ITMG_MAIN_EVENT_TYPE_PTT_DOWNLOAD_COMPLETE event
        // https://cloud.tencent.com/document/product/607/56341#.E4.B8.8B.E8.BD.BD.E8.AF.AD.E9.9F.B3.E6.96.87.E4.BB.B6
          ITMGContext.GetInstance(this).GetPTT().DownloadRecordedFile(_downloadurl, templedownload);
    }

    private void onPlayDownloadFileClick() {
        if (mIsPlaying) {
            return;
        }
        mIsPlaying = true;
        appendLog2MonitorView("Play download record file");
        String recordFilePath = mDownloadFileView.getText().toString().trim();

        // Step 9/12 play record voice, need handle ITMG_MAIN_EVENT_TYPE_PTT_PLAY_COMPLETE event
        // https://cloud.tencent.com/document/product/607/56341#.E6.92.AD.E6.94.BE.E8.AF.AD.E9.9F.B3
        ITMGContext.GetInstance(this).GetPTT().PlayRecordedFile(recordFilePath);
    }

    private void onRecognizeClick() {
        // Step 11/12 recognition voice, need handle ITMG_MAIN_EVENT_TYPE_PTT_SPEECH2TEXT_COMPLETE envent
        // https://cloud.tencent.com/document/product/607/56341#.E5.B0.86.E6.8C.87.E5.AE.9A.E7.9A.84.E8.AF.AD.E9.9F.B3.E6.96.87.E4.BB.B6.E8.AF.86.E5.88.AB.E6.88.90.E6.96.87.E5.AD.97
        String recFileUrl = mRecFileUrlView.getText().toString();
        if (!recFileUrl.isEmpty()) {
            ITMGContext.GetInstance(this).GetPTT().SpeechToText(recFileUrl);
        }
    }

    @Override
    public void OnEvent(ITMGType.ITMG_MAIN_EVENT_TYPE type, Intent data) {
        final int nErrCode = data.getIntExtra("result", 0);

        // Step 4/12 handle ITMG_MAIN_EVENT_TYPE_PTT_RECORD_COMPLETE event
        if (type == ITMGType.ITMG_MAIN_EVENT_TYPE.ITMG_MAIN_EVENT_TYPE_PTT_RECORD_COMPLETE) {
            mIsRecording = false;
            if (nErrCode ==0)
            {
                String recFilePath = data.getStringExtra("file_path");
                mRecFilePathView.setText(recFilePath);
                appendLog2MonitorView("Record Success local filepath:" + recFilePath);
            }
            else
            {
                appendLog2MonitorView("Record fail errorCode:" + nErrCode);
            }
        } else if (type == ITMGType.ITMG_MAIN_EVENT_TYPE.ITMG_MAIN_EVENT_TYPE_PTT_UPLOAD_COMPLETE) {
            // Step 6/12 handle ITMG_MAIN_EVENT_TYPE_PTT_UPLOAD_COMPLETE event
            if (nErrCode == 0)
            {
                String uploadUrl = data.getStringExtra("file_id");
                mRecFileUrlView.setText(uploadUrl);
                appendLog2MonitorView("Upload file success url:" + uploadUrl);
            } else
            {
                appendLog2MonitorView("Upload file fail errCode:" + nErrCode);
            }
        } else if (type == ITMGType.ITMG_MAIN_EVENT_TYPE.ITMG_MAIN_EVENT_TYPE_PTT_PLAY_COMPLETE) {
            // Step 10/12 handle ITMG_MAIN_EVENT_TYPE_PTT_PLAY_COMPLETE event
            mIsPlaying = false;
            if (nErrCode == 0) {
                appendLog2MonitorView("Play record file success");
            } else {
                appendLog2MonitorView("Play record file fail errCode:" + nErrCode);
            }
        } else if (type == ITMGType.ITMG_MAIN_EVENT_TYPE.ITMG_MAIN_EVENT_TYPE_PTT_DOWNLOAD_COMPLETE) {
            // Step 8/12 handle ITMG_MAIN_EVENT_TYPE_PTT_DOWNLOAD_COMPLETE event
            if (nErrCode == 0) {
                String downloadFilePath = data.getStringExtra("file_path");
                mDownloadFileView.setText(downloadFilePath);
                appendLog2MonitorView("Download record file success download filepath:" + downloadFilePath);
            } else {
                appendLog2MonitorView("Download record file fail errCode:" + nErrCode);
            }
        } else if (type == ITMGType.ITMG_MAIN_EVENT_TYPE.ITMG_MAIN_EVENT_TYPE_PTT_SPEECH2TEXT_COMPLETE) {
            // Step 12/12 handle ITMG_MAIN_EVENT_TYPE_PTT_SPEECH2TEXT_COMPLETE event
            if (nErrCode ==0)
            {
                //离线语音：10、语音转文字成功。
                String textString = data.getStringExtra("text");
                mRecognizeTextView.setText(textString);
            }
            else
            {
                appendLog2MonitorView("Voice recognition error:" + nErrCode);
            }
        } else if (type == ITMGType.ITMG_MAIN_EVENT_TYPE.ITMG_MAIN_EVENT_TYPE_PTT_STREAMINGRECOGNITION_IS_RUNNING) {
            // Step 1.2/3 handle ITMG_MAIN_EVENT_TYPE_PTT_STREAMINGRECOGNITION_IS_RUNNING event
            String textString = data.getStringExtra("text");
            mRecognizeTextView.setText(textString);
            appendLog2MonitorView("Voice recognition result:" + textString);
            mRecFilePathView.setText("");
            mRecFileUrlView.setText("STREAMINGRECOGNITION_IS_RUNNING");
        } else if (type == ITMGType.ITMG_MAIN_EVENT_TYPE.ITMG_MAIN_EVENT_TYPE_PTT_STREAMINGRECOGNITION_COMPLETE) {
            // Step 1.3/3 handle ITMG_MAIN_EVENT_TYPE_PTT_STREAMINGRECOGNITION_COMPLETE event
            mIsRecording = false;
            if (nErrCode ==0)
            {
                String recordfilePath = data.getStringExtra("file_path");
                mRecFilePathView.setText(recordfilePath);

                String recordFileUrl = data.getStringExtra("file_id");
                mRecFileUrlView.setText(recordFileUrl);
            }
            else
            {
                appendLog2MonitorView("Record and recognition fail errCode:" + nErrCode);
            }
        }
    }

    private void appendLog2MonitorView(String text) {
        String logText = mLogMonitorView.getText().toString();
        if (!logText.isEmpty()) {
            logText = logText + "\n" + text;
        } else {
            logText = text;
        }
        mLogMonitorView.setText(logText);
        mLogHostView.fullScroll(View.FOCUS_DOWN);
    }
}
