package com.tencent.gme.audio.apiexample;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
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 androidx.appcompat.app.ActionBar;

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

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class TranslateTextActivity  extends BaseActivity
        implements View.OnClickListener, TMGDispatcherBase, CompoundButton.OnCheckedChangeListener {

    private EditText mTranslateLanguageView;

    private Spinner mSourceLanguageSpinner;

    private EditText mSourceEditText;

    private TextView mTranslateResultTextView;

    private final CheckBox[] mTranslateCbs = new CheckBox[18];
    private final String[] mTranslateCodes = new String[]{"cmn-Hans-CN", "cmn-Hant-TW", "en-US",
            "de-DE", "pt-PT", "es-ES", "tr-TR", "ar-SA", "ru-RU", "fr-FR", "it-IT", "pl-PL",
            "cs-CZ", "fi-FI", "af-ZA", "ur-IN", "hi-IN", "bn-BD"};

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

        initActionBar("Translate Text");

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

        TMGCallbackDispatcher.getInstance().registerSubDispatcher(this);

        byte[] authBuffer = GMEAuthBufferHelper.getInstance().createAuthBuffer("");
        ITMGContext.GetInstance(this).GetPTT().ApplyPTTAuthbuffer(authBuffer);
    }

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

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

        mSourceLanguageSpinner = findViewById(R.id.spSourceLanguage);
        mTranslateLanguageView = findViewById(R.id.etTranslateLanguage);
        mSourceEditText = findViewById(R.id.etSourceText);
        mTranslateResultTextView = findViewById(R.id.tvTranslateResult);

        mTranslateCbs[0] = findViewById(R.id.cb_translate_00);
        mTranslateCbs[1] = findViewById(R.id.cb_translate_01);
        mTranslateCbs[2] = findViewById(R.id.cb_translate_02);
        mTranslateCbs[3] = findViewById(R.id.cb_translate_03);
        mTranslateCbs[4] = findViewById(R.id.cb_translate_04);
        mTranslateCbs[5] = findViewById(R.id.cb_translate_05);
        mTranslateCbs[6] = findViewById(R.id.cb_translate_06);
        mTranslateCbs[7] = findViewById(R.id.cb_translate_07);
        mTranslateCbs[8] = findViewById(R.id.cb_translate_08);
        mTranslateCbs[9] = findViewById(R.id.cb_translate_09);
        mTranslateCbs[10] = findViewById(R.id.cb_translate_10);
        mTranslateCbs[11] = findViewById(R.id.cb_translate_11);
        mTranslateCbs[12] = findViewById(R.id.cb_translate_12);
        mTranslateCbs[13] = findViewById(R.id.cb_translate_13);
        mTranslateCbs[14] = findViewById(R.id.cb_translate_14);
        mTranslateCbs[15] = findViewById(R.id.cb_translate_15);
        mTranslateCbs[16] = findViewById(R.id.cb_translate_16);
        mTranslateCbs[17] = findViewById(R.id.cb_translate_17);

        for (int i = 0; i < mTranslateCbs.length; i++) {
            mTranslateCbs[i].setOnCheckedChangeListener(this);
            mTranslateCbs[i].setText(mTranslateCodes[i]);
        }
    }

    private String getTranslateCode() {
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < mTranslateCbs.length; i++) {
            if (mTranslateCbs[i].isChecked()) {
                sb.append(",");
                sb.append(mTranslateCodes[i]);
            }
        }
        if (sb.length() > 1) {
            return sb.substring(1);
        } else {
            return sb.toString();
        }

    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        mTranslateLanguageView.setText(getTranslateCode());
    }

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

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

    private void onTranslateTextClick() {
        String sourceText = mSourceEditText.getText().toString();
        String sourceLanguage = mSourceLanguageSpinner.getSelectedItem().toString();
        String translateLanguage = mTranslateLanguageView.getText().toString();
        int ret = ITMGContext.GetInstance(this).GetPTT().TranslateText(sourceText, sourceLanguage, translateLanguage);
        if (ret != AVError.AV_OK) {
            Toast.makeText(this, "TranslateText error, code = " + ret, Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void OnEvent(ITMGType.ITMG_MAIN_EVENT_TYPE type, Intent data) {
        final int nErrCode = data.getIntExtra("result", -2);
        if (type == ITMGType.ITMG_MAIN_EVENT_TYPE
                .ITMG_MAIN_EVENT_TYPE_PTT_TRANSLATE_TEXT_COMPLETE) {
            if (nErrCode == 0) {
                appendLog2MonitorView(parseTranslateResult(data));
            } else {
                appendLog2MonitorView( "TranslatedText error:" + nErrCode);
            }
        }
    }

    private String parseTranslateResult(Intent translateIntent) {
        StringBuilder sb = new StringBuilder();
        String  source_language_code = translateIntent.getStringExtra("source_language_code");
        if (!source_language_code.isEmpty()) {
            sb.append("source_language_code:");
            sb.append(source_language_code);
            sb.append("\n");
        }
        String  source_text = translateIntent.getStringExtra("source_text");
        if (!source_text.isEmpty()) {
            sb.append("source_text:");
            sb.append(source_text);
            sb.append("\n");
        }
        Bundle extras = translateIntent.getExtras();
        Object targetValue = extras.get("target_text");
        if (targetValue != null && targetValue instanceof Intent[]) {
            Intent targetIntents[] = (Intent[])targetValue;
            for (int i = 0; i < targetIntents.length; i++) {
                String target_language_code = targetIntents[i].getStringExtra("target_language_code");
                String translated_text = targetIntents[i].getStringExtra("translated_text");
                if (!target_language_code.isEmpty() && !translated_text.isEmpty()) {
                    sb.append(target_language_code);
                    sb.append(":");
                    sb.append(translated_text);
                    sb.append("\n");
                }
            }
        }
        return sb.toString();
    }

    private void appendLog2MonitorView(String text) {
        mTranslateResultTextView.setText(text);
    }
}
