package com.tencent.gme.audio.apiexample;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

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

import java.io.InputStream;
import java.io.File;
import java.io.FileOutputStream;


public class MainActivity extends BaseActivity implements View.OnClickListener {
    static final String g_APPID = AppID To Replace Here https://cloud.tencent.com/document/product/607/10782;
    static final String g_APPKEY = AppKey To Replace Here https://cloud.tencent.com/document/product/607/10782;

    private EditText mAppIdView, mKeyView, mUserIDView;
    private Button mRealTimeVoiceBtn, mPttBtn;
    private Button mTextToSpeechBtn;
    private Button mTranslateTextBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initViews();
        mAppIdView.setText(g_APPID);
        mKeyView.setText(g_APPKEY);
        mUserIDView.setText(String.valueOf(System.currentTimeMillis() % 10000 + 10000));

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

        copyFile("license.lic");
    }

    public void copyFiles(String assetsPath) {
        try {
            String[] fileNames = this.getApplicationContext().getAssets().list(assetsPath);
            if (fileNames.length > 0) {
                String folderPath = this.getExternalFilesDir(null).toString() + "/" + assetsPath;
                File file = new File(folderPath);
                boolean ret = file.mkdirs();
                for (String fileName : fileNames) {
                    copyFiles(assetsPath + "/" + fileName);
                }
            } else {
                // 若是是文件
                copyFile(assetsPath);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void copyFile(String fileName) {
        InputStream is = null;
        FileOutputStream fos = null;
        try {
            String filePath = this.getExternalFilesDir(null).toString() + "/" + fileName;
            is = this.getApplicationContext().getAssets().open(fileName);
            fos = new FileOutputStream(filePath);
            byte[] buffer = new byte[1024];
            int byteCount = 0;
            while ((byteCount = is.read(buffer)) != -1) {
                fos.write(buffer, 0, byteCount);
            }
            fos.flush();//刷新缓冲区

        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            if (is != null) {
                is.close();
            }
            if (fos != null) {
                fos.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

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

        mAppIdView = findViewById(R.id.etAppId);
        mKeyView = findViewById(R.id.etKey);
        mUserIDView = findViewById(R.id.etUserID);

        findViewById(R.id.btnInit).setOnClickListener(this);
        findViewById(R.id.btnUnInit).setOnClickListener(this);

        mRealTimeVoiceBtn = findViewById(R.id.btnRealTimeVoice);
        mRealTimeVoiceBtn.setOnClickListener(this);
        mRealTimeVoiceBtn.setEnabled(false);

        mPttBtn = findViewById(R.id.btnPTT);
        mPttBtn.setOnClickListener(this);
        mPttBtn.setEnabled(false);

        mTextToSpeechBtn = findViewById(R.id.btnTextToSpeech);
        mTextToSpeechBtn.setOnClickListener(this);
        mTextToSpeechBtn.setEnabled(false);

        mTranslateTextBtn = findViewById(R.id.btnTranslateText);
        mTranslateTextBtn.setOnClickListener(this);
        mTranslateTextBtn.setEnabled(false);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.btnInit) {
            onInitClick();
        } else if (id == R.id.btnUnInit) {
            onUnInitClick();
        } else if (id == R.id.btnRealTimeVoice) {
            onRealTimeVoiceClick();
        } else if (id == R.id.btnPTT) {
            onVoiceMessageRecognitionClick();
        } else if (id == R.id.btnTextToSpeech) {
            onTextToSpeechClick();
        } else if (id == R.id.btnTranslateText) {
            onTranslateTextClick();
        }
    }



    // handle Init button click
    private void onInitClick() {
        String appId = mAppIdView.getText().toString().trim();
        if (TextUtils.isEmpty(appId)) {
            showToast("Please input AppId");
            return;
        }
        String key = mKeyView.getText().toString().trim();
        if (TextUtils.isEmpty(key)) {
            showToast("Please input Key");
            return;
        }

        String userID = mUserIDView.getText().toString().trim();
        if (TextUtils.isEmpty(userID)) {
            showToast("Please input userID");
            return;
        }
        // step 1/11: get ITMGContext
        // https://cloud.tencent.com/document/product/607/15210#.E8.8E.B7.E5.8F.96.E5.8D.95.E4.BE.8B
        ITMGContext tmgContext = ITMGContext.GetInstance(this);

        // step 2/11: Set GME CallBack
        //https://cloud.tencent.com/document/product/607/15210#.E6.B3.A8.E5.86.8C.E5.9B.9E.E8.B0.83
        tmgContext.SetTMGDelegate(TMGCallbackDispatcher.getInstance());

        // Step 3/11 Init GME
        // https://cloud.tencent.com/document/product/607/15210#.3Ca-id.3D.22init.22.3E.E5.88.9D.E5.A7.8B.E5.8C.96-sdk.3C.2Fa.3E
        int nRet = tmgContext.Init(appId, userID);
        if (nRet == AVError.AV_OK) {
            GMEAuthBufferHelper.getInstance().setGMEParams(appId, key, userID);

            // Step 4/11: Poll to trigger callback
            // https://cloud.tencent.com/document/product/607/15210#.3Ca-id.3D.22poll.22.3E.E8.A7.A6.E5.8F.91.E4.BA.8B.E4.BB.B6.E5.9B.9E.E8.B0.83.3C.2Fa.3E
            EnginePollHelper.createEnginePollHelper();

            showToast("Init success");
        } else if (nRet == AVError.AV_ERR_HAS_IN_THE_STATE) // 已经初始化过了,可以认为本次操作是成功的
        {
            showToast("Init success");
        } else {
            showToast("Init error errorCode:" + nRet);
        }

        mRealTimeVoiceBtn.setEnabled(true);
        mPttBtn.setEnabled(true);
        mTextToSpeechBtn.setEnabled(true);
        mTranslateTextBtn.setEnabled(true);
    }

    // handle unInit button click
    private void onUnInitClick() {
        // 反初始化
        // https://cloud.tencent.com/document/product/607/15210#.3Ca-id.3D.22uninit.22.3E.E5.8F.8D.E5.88.9D.E5.A7.8B.E5.8C.96-sdk.3C.2Fa.3E
        ITMGContext.GetInstance(this).Uninit();

        mRealTimeVoiceBtn.setEnabled(false);
        mPttBtn.setEnabled(false);
        mTextToSpeechBtn.setEnabled(false);
        mTranslateTextBtn.setEnabled(false);
    }

    // handle Real time voice button click
    private void onRealTimeVoiceClick() {
        Intent i = new Intent(this, RealTimeVoiceActivity.class);
        this.startActivity(i);
    }

    // handle voice message & recognition button click
    private void onVoiceMessageRecognitionClick() {
        Intent i = new Intent(this, VoiceMessageRecognitionActivity.class);
        this.startActivity(i);
    }

    // handle Text To Speech button click
    private void onTextToSpeechClick() {
        Intent i = new Intent(this, TextToSpeechActivity.class);
        this.startActivity(i);
    }

    private void onTranslateTextClick() {
        Intent i = new Intent(this, TranslateTextActivity.class);
        this.startActivity(i);
    }
}