package com.efounder.chat.activity;

import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.core.xml.StubObject;
import com.efounder.chat.R;
import com.efounder.chat.http.OpenEthRequest;
import com.efounder.chat.struct.MessageChildTypeConstant;
import com.efounder.chat.struct.StructFactory;
import com.efounder.chat.utils.AESSecretUtil;
import com.efounder.chat.utils.RSAUtil;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.message.manager.JFMessageManager;
import com.efounder.message.struct.IMStruct002;
import com.efounder.util.ToastUtil;
import com.efounder.utils.ResStringUtil;
import com.utilcode.util.ClickUtils;
import com.utilcode.util.ToastUtils;

import org.json.JSONObject;

import java.util.Hashtable;


public class SecretLetterActivity extends BaseActivity {

    private TextView tvTitle;
    private TextView tvSend;
    private ImageView ivShowPassword;
    private EditText etLetterPassword;
    private EditText etSecertLetter;
    private StubObject mStubObject;
    private Hashtable mHashtable;
    private String mToUserId;

    private Bundle mBundle;
    private String publicKey;
    private String RSAPublicKey;

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

        mBundle = getIntent().getExtras();
        mStubObject = (StubObject) mBundle.getSerializable("stubObject");
        mHashtable = mStubObject.getStubTable();
        mToUserId = (String) mHashtable.get("toUserId");

        initData();
        initView();
        etLetterPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (etLetterPassword.getText().toString().contains(" ")) {
                    ToastUtils.showShort(R.string.common_text_pwd_not_be_blanket);
                    etLetterPassword.setText(etLetterPassword.getText().toString().trim());
                    etLetterPassword.setSelection(etLetterPassword.getText().toString().length());
                }
            }
        });
    }

    private void initData() {
        OpenEthRequest.getUserEthByImUserId(this, Integer.valueOf(mToUserId), new OpenEthRequest.EthRequestListener() {
            @Override
            public void onSuccess(String ethAddress, String publicKey1, String RSAPublicKey1) {
                publicKey = publicKey1;
                RSAPublicKey = RSAPublicKey1;
            }

            @Override
            public void onFail(String error) {
                ToastUtil.showToast(SecretLetterActivity.this, ResStringUtil.getString(R.string.wrchatview_not_get_key));
            }
        });
    }

    private void initView() {
        tvTitle = (TextView) findViewById(R.id.tv_title);
        tvSend = (TextView) findViewById(R.id.tv_send);

        ivShowPassword = (ImageView) findViewById(R.id.iv_show_password);
        etLetterPassword = (EditText) findViewById(R.id.et_letter_password);
        etSecertLetter = (EditText) findViewById(R.id.et_secert_letter);
        ImageView backImageView = (ImageView) findViewById(R.id.iv_back);
        backImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(etLetterPassword.getWindowToken(), 0);
                finish();
            }
        });

        ivShowPassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (etLetterPassword.getInputType() != InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD) {
                    etLetterPassword.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                    ivShowPassword.setImageResource(R.drawable.icon_show_password);
                } else {
                    etLetterPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                    ivShowPassword.setImageResource(R.drawable.icon_hide_password);
                }
                String pwd = etLetterPassword.getText().toString().trim();
                if (!TextUtils.isEmpty(pwd))
                    etLetterPassword.setSelection(pwd.length());
            }
        });

        ClickUtils.applySingleDebouncing(tvSend, new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String pwd = etLetterPassword.getText().toString().trim();
                if (pwd.equals("")) {
                    ToastUtils.showShort(R.string.common_text_please_inputpwd);
                    etLetterPassword.setText("");
                    etLetterPassword.requestFocus();
                    return;
                }
                String message = etSecertLetter.getText().toString();
                if (message.equals("")) {
                    ToastUtil.showToast(SecretLetterActivity.this, ResStringUtil.getString(R.string.wrchatview_secret_not_null));

                    return;
                }
//                if (publicKey == null || "".equals(publicKey)) {
//                    ToastUtil.showToast(SecretLetterActivity.this, "公钥不能为空");
//                    return;
//                }
                if (RSAPublicKey == null || "".equals(RSAPublicKey)) {
                    ToastUtil.showToast(SecretLetterActivity.this, getResources().getString(R.string.secret_activity_no_publickey));

                    return;
                }

                sendMessage(pwd);

            }
        });


    }

    private void sendMessage(String pwd) {
        AESSecretUtil aesSecretUtil = new AESSecretUtil(pwd);
        String message = etSecertLetter.getText().toString();
        String secretMessage = aesSecretUtil.encrypt(message);
        // String secretPwd = CertificateUtil.encrypt(pwd, publicKey);
        //todo 更改加密方式
        String secretPwd = null;
        try {
            secretPwd = RSAUtil.encryptByPublicKey(pwd, RSAPublicKey);
        } catch (Exception e) {
            e.printStackTrace();
            ToastUtil.showToast(SecretLetterActivity.this, ResStringUtil.getString(R.string.wrchatview_password_fail));
            return;
        }

//        {"content":"加密的字符","password":"加密的密码"}    密信的 json
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("content", secretMessage);
            jsonObject.put("password", secretPwd);

            IMStruct002 imStruct002 = new IMStruct002();
            imStruct002.setBody(jsonObject.toString().getBytes("UTF-8"));
            imStruct002.setTime(System.currentTimeMillis());
            imStruct002.setFromUserId(Integer.parseInt(EnvironmentVariable.getUserID()));
            imStruct002.setToUserType(StructFactory.TO_USER_TYPE_PERSONAL);
            imStruct002.setToUserId(Integer.parseInt(mToUserId));
            imStruct002.setMessageChildType(MessageChildTypeConstant.subtype_secret_text);

            JFMessageManager.getInstance().sendMessage(imStruct002);

            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(etLetterPassword.getWindowToken(), 0);
            finish();

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

    }

}
