package com.tencent.gme.audio.apiexample;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.gme.TMG.ITMGContext;
import com.gme.av.sdk.AVError;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.gme.TMG.ITMGContext;

import java.util.Timer;
import java.util.TimerTask;

public class StreamToTextActivity   extends BaseActivity
        implements View.OnClickListener, View.OnTouchListener, TMGDispatcherBase {

    private Spinner mSourceLanguageSpinner;

    private TextView mTranslateResultTextView;
    private Button mPushButton;

    private final String[] mTranslateCodes = new String[]{"en-US", "cmn-Hant-TW", "vi-VN",
            "cmn-Hans-CN", "th-TH", "ko-KR", "fr-FR", "de-DE", "ru-RU", "tr-TR", "pt-PT",
            "pt-BR", "es-ES", "it-IT", "nl-NL", "ms-MY", "id-ID", "ar-SA", "ja-JP"};

    int  index = 1;

    private Timer timer;
    private TimerTask task;
    int count;
    private boolean isPush;

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

        initViews();
        //启动一个service用于提高APP的后台优先级，避免部分机型使用openssl时播放声音异常
        Intent intent = new Intent(this, AudioService.class);
        startService(intent);

        TMGCallbackDispatcher.getInstance().registerSubDispatcher(this);
    }

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

    private void initViews() {
        findViewById(R.id.btnClear).setOnClickListener(this);
        findViewById(R.id.btnStreamStart).setOnClickListener(this);

        findViewById(R.id.btnStreamStart).setOnTouchListener(this);

        mSourceLanguageSpinner = findViewById(R.id.spSourceLanguage);
        mTranslateResultTextView = findViewById(R.id.tvTranslateResult);
        mPushButton = findViewById(R.id.btnStreamStart);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_dropdown_item_1line, android.R.id.text1,mTranslateCodes);
        mSourceLanguageSpinner.setAdapter(adapter);
        mSourceLanguageSpinner.setSelection(3);
        timer = new Timer();
        count = 60;
        isPush = false;
        task = new TimerTask() {
            @Override
            public void run() {
                if (!isPush) {
                    return;
                }

                count--;
                if (count == 0) {
                    stopStream();
                    isPush = false;
                    mPushButton.post(new Runnable() {
                        @Override
                        public void run() {
                            mPushButton.setText("Push to talk");
                        }
                    });
                    return;
                }
                mPushButton.post(new Runnable() {
                    @Override
                    public void run() {
                        mPushButton.setText(String.format("%d", count));
                    }
                });
            }
        };
        timer.schedule(task, 0, 1000);
    }

    @Override
    public void onClick(View v) {
        final int id = v.getId();
        if (id == R.id.btnClear) {
            clear();
        }
    }

    private void clear() {
        mTranslateResultTextView.setText("");
    }

    private void stopStream() {
        ITMGContext.GetInstance(this).GetPTT().StopRecording();
    }

    @Override
    public void OnEvent(ITMGContext.ITMG_MAIN_EVENT_TYPE type, Intent data) {
        final int nErrCode = data.getIntExtra("result", -2);
        final  Intent templeData = data;
        switch (type) {
            case ITMG_MAIN_EVNET_TYPE_PTT_STREAMINGRECOGNITION_COMPLETE: {
                //流式离线语音回调。
                Handler mainHander = new Handler(Looper.getMainLooper());
                mainHander.post(new Runnable() {
                    @Override
                    public void run() {
                        if (nErrCode == 0) {

                            String textString = templeData.getStringExtra("text");
                            mTranslateResultTextView.setText(textString);
                        } else if (nErrCode == 4098) {
                            showToast(String.format("Microphone Not authorized"));
                        } else if (nErrCode == 4103) {
                            showToast(String.format("The recording time is too short"));
                        } else {
                            showToast(String.format(
                                    "Streaming voice to text failed, error code：%d", nErrCode));
                        }
                    }
                });
            }
            break;
            case ITMG_MAIN_EVNET_TYPE_PTT_STREAMINGRECOGNITION_IS_RUNNING: {
                //流式离线语音回调。
                Handler mainHander = new Handler(Looper.getMainLooper());
                mainHander.post(new Runnable() {
                    @Override
                    public void run() {
                        if (nErrCode == 0) {

                            String textString = templeData.getStringExtra("text");
                            mTranslateResultTextView.setText(textString);
                        } else {
                            showToast(String.format(
                                    "ITMG_MAIN_EVNET_TYPE_PTT_STREAMINGRECOGNITION_IS_RUNNING，"
                                            + "错误代码：%d", nErrCode));
                        }
                    }
                });
                break;
            }
            default:
                break;
        }
    }

    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        if (view.getId() == R.id.btnStreamStart) {
            if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                isPush = false;
                mPushButton.setText("Push to talk");
                ITMGContext.GetInstance(this).GetPTT().StopRecording();
            }
            if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
                String  temple = getExternalFilesDir(null).getAbsolutePath()
                        + "/test_" + (index++) + ".ptt";
                String sourceLanguage = mSourceLanguageSpinner.getSelectedItem().toString();
                ITMGContext.GetInstance(this).GetPTT().StartRecordingWithStreamingRecognition(
                        temple,sourceLanguage);
                count = 60;
                isPush = true;
            }
        }
        return false;
    }
}