package com.penpower.transtarjctest;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.TextView;

import com.transtar.JCDictSearch;

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

public class MainActivity extends AppCompatActivity {

    private Button mButtonDict;
    private TextView mTextViewTranslated;
    private WebView mWebViewDictResult;
    private static final int TRANSLATION_MODE_BASIC = 0x00041; //1)  基本内容：mode=0x00041。  返回内容包括：单一译文；
    private static final int TRANSLATION_MODE_ADVANCED = 0x00070; //2)  带例句：mode=0x00070。 返回内容包括：原词 ,音标 ,基本解释 (不带例句)；
    private static final int TRANSLATION_MODE_PROFESSIONAL = 0x07474; //3)  全部内容：mode=0x07474。返回内容包括：原词 ,音标 ,词尾变化，基本解释 (带例句) ,[辨析]，[同义词]，[反义词]

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mTextViewTranslated = (TextView) findViewById(R.id.Tv_translate_result);
        mWebViewDictResult = (WebView) findViewById(R.id.dict_result);
        mButtonDict = (Button) findViewById(R.id.button_translate);
        long fsize = Copyto(this, R.raw.jpdict,  "jpdict.idx");
        if (mButtonDict != null) {
            mButtonDict.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int iResult = initCJEdataFile();
                    Log.d("TranstarJCTest", "initCJEdataFile() result = " + iResult);
                    if (iResult == 0) {
                        mTextViewTranslated.setText(doCJTranslate(0, getString(R.string.Com_dict_key)));
                        mWebViewDictResult.loadData(getCJDictHtml(0, getString(R.string.Com_dict_key)),
                                "text/html",
                                "utf-16le");
                    } else {
                        if (mTextViewTranslated != null) {
                            mTextViewTranslated.setText(R.string.Com_dict_init_fail);
                        }
                        if (mWebViewDictResult != null) {
                            mWebViewDictResult.loadUrl("about:blank");
                        }
                    }
                }
            });
        }
    }

    private int initCJEdataFile() {
        String path = getApplicationInfo().dataDir + "/";
        JCDictSearch.EndDictJC();
        int x = JCDictSearch.IniDictJC(path.getBytes());
        return x;
    }

    private String doCJTranslate(int aLang, String aKey) {
        byte[] tranResBytes = null;
        byte[] srcByte = null;
        String TranslateWord = null;

        aKey += '\0';
        tranResBytes = JCDictSearch.TranslateWordJC(TRANSLATION_MODE_BASIC, aKey);
        try {
            if (tranResBytes != null)
                TranslateWord = new String(tranResBytes, "utf-16le");

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return TranslateWord;
    }

    private String getCJDictHtml(int aLang, String aKey) {
        byte[] explainResBytes = null;
        byte[] srcByte = null;
        String ExplainWord = null;

        aKey += '\0';
        explainResBytes = JCDictSearch.TranslateWordJC(TRANSLATION_MODE_PROFESSIONAL, aKey);
        try {
            if (explainResBytes != null)
                ExplainWord = new String(explainResBytes, "utf-16le");

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return ExplainWord;
    }


    public int Copyto(Context aContext, int aRawResId1, String aTargetName) {
        final int BUFFER_SIZE = 65535;
        int nInputStreamSize = 0;
        String filename = aContext.getApplicationInfo().dataDir + "/" + aTargetName;

        File file_new = null;
        OutputStream out = null;
        byte[] buf = null;

            file_new = new File(filename);
            buf = new byte[BUFFER_SIZE];

        if (!file_new.exists()) {
            try {
                out = new FileOutputStream(file_new);

                InputStream in = aContext.getResources().openRawResource(aRawResId1);
                int len = 0;
                while ((len = in.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }

                for (byte b : buf) {
                    b = 0;
                }
                in.close();

                out.close();

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        else if (file_new.exists()) {
            nInputStreamSize += file_new.length();
        }

        return nInputStreamSize;
    }
}
