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 com.gme.TMG.ITMGContext;
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);

        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(ITMGContext.ITMG_MAIN_EVENT_TYPE type, Intent data) {
        final int nErrCode = data.getIntExtra("result", -2);
        if (type == ITMGContext.ITMG_MAIN_EVENT_TYPE
                .ITMG_MAIN_EVNET_TYPE_PTT_TRANSLATE_TEXT_COMPLETE) {
            if (nErrCode == 0) {
                String textString = data.getStringExtra("translatedText");
                appendLog2MonitorView(parseResult(textString));
            } else {
                Toast.makeText(this, "TranslatedText error:"
                        + nErrCode, Toast.LENGTH_LONG).show();
            }
        }
    }

    private String parseResult(String source) {
        StringBuilder sb = new StringBuilder();
        try {
            JSONObject root = new JSONObject(source);
            String sourceLanguage = root.getString("source_language_code");
            if (!sourceLanguage.isEmpty()) {
                sb.append("sourceLanguage:");
                sb.append(sourceLanguage);
                sb.append("\n");
            }

            JSONArray arrayText = root.getJSONArray("target_text");
            int size = arrayText.length();
            for (int i = 0; i < size; i++) {
                JSONObject obj = arrayText.getJSONObject(i);
                String code = obj.getString("target_language_code");
                String text = obj.getString("translated_text");
                sb.append(code);
                sb.append(":");
                sb.append(text);
                sb.append("\n");
            }
        } catch (JSONException e) {
            return e.toString();
        }
        return sb.toString();
    }

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