package com.efounder.chat.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.core.xml.StubObject;
import com.efounder.chat.R;
import com.efounder.chat.adapter.SecretImageAdapter;
import com.efounder.chat.http.OpenEthRequest;
import com.efounder.chat.utils.AESSecretUtil;
import com.efounder.chat.utils.ImageUtil;
import com.efounder.chat.utils.RSAUtil;
import com.efounder.pansoft.chat.input.SecretInputView;
import com.efounder.pansoft.chat.photo.JFMessagePicturePickView;
import com.efounder.pansoft.chat.photo.JFPicturePickPhotoWallActivity;
import com.efounder.util.AppContext;
import com.efounder.util.ToastUtil;
import com.efounder.utils.ResStringUtil;
import com.utilcode.util.FileIOUtils;
import com.utilcode.util.FileUtils;
import com.utilcode.util.KeyboardUtils;
import com.utilcode.util.ToastUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

import static com.efounder.pansoft.chat.photo.JFMessagePicturePickView.REQUEST_PIC_SELECTE_CODE;

/**
 * @author wwl
 * 密图
 */
public class SecretImageActivity extends BaseActivity implements View.OnClickListener {

    public static final int SECRET_IMAGE_RESULT_CODE = 1232;
    private TextView tvSend;
    private ImageView ivBack, ivShowPassword;
    private GridView gridView;
    private EditText etPassword;
    private SecretImageAdapter adapter;

    private boolean isShowPassword = false;//是否显示密码
    private List<String> urls = new ArrayList<>();//给adapter传入的图片list
    private LinkedList<String> mPictureList = new LinkedList<>();//和选图联动的图片list
    private boolean isRawPic = false;//是否是原图
    private int userId;//对方的userId
    private String ethAddress , publicKey, RSAPublicKey;
    private String secretPwd;//加密后的密码
    private int maxNum = 9;//可选择的最大照片数


    private Disposable compressDisposable;
    private Disposable encreptDisposable;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_wechat_activity_secret_image);
        //获取userId
        if (getIntent().getSerializableExtra("stubObject") != null) {
            userId = ((StubObject) getIntent().getSerializableExtra("stubObject")).getInt("toUserId", 0);
        }
        //通过userId获取公钥
        getUserPublicKey(userId);
        initView();
        etPassword.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 (etPassword.getText().toString().contains(" ")) {
                    ToastUtils.showShort(R.string.common_text_pwd_not_be_blanket);
                    etPassword.setText(etPassword.getText().toString().trim());
                    etPassword.setSelection(etPassword.getText().toString().length());
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.iv_back) {
            KeyboardUtils.hideSoftInput(etPassword);
            finish();
        } else if (id == R.id.tv_send) {
            //发送消息
            if (etPassword.getText().toString().trim().equals("")) {
                ToastUtils.showShort(R.string.common_text_please_inputpwd);
                etPassword.setText("");
                etPassword.requestFocus();
                return;
            }
            if (publicKey== null || RSAPublicKey ==null){
                ToastUtil.showToast(SecretImageActivity.this, getResources().getString(R.string.secret_activity_no_publickey));                return;
            }
            sendSecretImg();
        } else if (id == R.id.iv_show_password) {
            //显示隐藏密码
            if (isShowPassword) {
                ivShowPassword.setImageDrawable(getResources().getDrawable(R.drawable.icon_show_password));
                etPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                etPassword.setSelection(etPassword.getText().toString().trim().length());
                isShowPassword = false;
            } else {
                ivShowPassword.setImageDrawable(getResources().getDrawable(R.drawable.icon_hide_password));
                etPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
                etPassword.setSelection(etPassword.getText().toString().trim().length());
                isShowPassword = true;
            }
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == JFMessagePicturePickView.REQUEST_PIC_SELECTE_CODE
                && resultCode == RESULT_OK) {
            //图库选择照片
            urls.clear();
            urls.addAll((ArrayList<String>) data.getExtras().get("mSelectedPics"));
            urls.add("add");
            mPictureList.clear();
            mPictureList.addAll((ArrayList<String>) data.getExtras().get("mSelectedPics"));

            isRawPic = data.getExtras().getBoolean("isRawPic");

            adapter.notifyDataSetChanged();
        }
    }

    private void initView() {
        //发送按钮
        tvSend = (TextView) findViewById(R.id.tv_send);
        tvSend.setOnClickListener(this);
        //返回按钮
        ivBack = (ImageView) findViewById(R.id.iv_back);
        ivBack.setOnClickListener(this);
        //显示/隐藏密码
        ivShowPassword = (ImageView) findViewById(R.id.iv_show_password);
        ivShowPassword.setOnClickListener(this);
        //密码输入
        etPassword = (EditText) findViewById(R.id.et_password);
        gridView = (GridView) findViewById(R.id.gridView);
        //这是最后的加号
        urls.add("add");
        adapter = new SecretImageAdapter(this, urls);
        gridView.setAdapter(adapter);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //加号，选择图片
                if (position == urls.size() - 1) {
                    Intent intent = new Intent(SecretImageActivity.this, JFPicturePickPhotoWallActivity.class);
                    intent.putExtra("mPictureList", mPictureList);
                    intent.putExtra("maxNum", maxNum);//可选择的最大照片数
                    intent.putExtra("sendBtnName", getResources().getString(R.string.common_text_confirm));
                    startActivityForResult(intent, REQUEST_PIC_SELECTE_CODE);
                    overridePendingTransition(R.anim.push_bottom_in, R.anim.push_bottom_out);
                }
            }
        });
        adapter.setOnImgRemovedListener(new SecretImageAdapter.OnImgRemovedListener() {
            @Override
            public void onImgRemoved(int position) {
                urls.remove(position);
                mPictureList.remove(position);
                adapter.notifyDataSetChanged();
            }
        });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (compressDisposable != null) {
            compressDisposable.dispose();
        }
        if (encreptDisposable != null) {
            encreptDisposable.dispose();
        }

    }

    /**
     * 发送图片
     */
    private void sendSecretImg() {

        if (mPictureList.size()==0){
            ToastUtil.showToast(AppContext.getInstance(),ResStringUtil.getString(R.string.wrchatview_image_not_null));
            return;
        }
        if (!isRawPic) {
            //压缩图片
            compressImage(mPictureList);
        } else {
            //加密图片
            encryptImg(mPictureList);
        }

    }

    //压缩图片
    private void compressImage(final List<String> mPictureList) {
        compressDisposable = Observable.create(new ObservableOnSubscribe<List<String>>() {
            @Override
            public void subscribe(ObservableEmitter<List<String>> emitter) throws Exception {
                List<String> compressList = new ArrayList<>();
                for (String url : mPictureList) {
                    if (!ImageUtil.isGifFile((new File(url)))) {
                        ImageUtil.saveNewImage(url, 1280, 1280);
                        compressList.add(ImageUtil.chatpath + ImageUtil.getFileName(url) + ".pic");
//                        encryptImg(ImageUtil.chatpath + ImageUtil.getFileName(url) + ".pic");
//                        encryptList.add(ImageUtil.encryptImgPath + ImageUtil.getFileName(url) + ".pic");
                    } else {
                        compressList.add(url);
//                        encryptImg(url);
//                        encryptList.add(ImageUtil.encryptImgPath + ImageUtil.getFileName(url));
                    }
                }
                emitter.onNext(compressList);
            }
        }).subscribeOn(Schedulers.io()).doOnSubscribe(new Consumer<Disposable>() {
            @Override
            public void accept(Disposable disposable) throws Exception {
                SecretInputView.showTcLoading(SecretImageActivity.this, ResStringUtil.getString(R.string.wrchatview_image_compression));
            }
        }).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<List<String>>() {
            @Override
            public void accept(List<String> strings) throws Exception {
                SecretInputView.dismissTcLoading();
                encryptImg(strings);
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {
                ToastUtil.showToast(SecretImageActivity.this, ResStringUtil.getString(R.string.wrchatview_image_compression_fail));
            }
        });


    }

    //加密图片
    private void encryptImg(final List<String> filePaths) {
        encreptDisposable = Observable.create(new ObservableOnSubscribe<ArrayList<String>>() {
            @Override
            public void subscribe(ObservableEmitter<ArrayList<String>> emitter) throws Exception {
                ArrayList<String> encreptyptList = new ArrayList<>();
                for (String path : filePaths) {
                    encryptImg(path);
                    encreptyptList.add(ImageUtil.encryptImgPath + ImageUtil.getFileName(path));
                }
                emitter.onNext(encreptyptList);
            }
        }).subscribeOn(Schedulers.io()).doOnSubscribe(new Consumer<Disposable>() {
            @Override
            public void accept(Disposable disposable) throws Exception {
                SecretInputView.showTcLoading(SecretImageActivity.this, ResStringUtil.getString(R.string.wrchatview_image_encryption));
            }
        }).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<ArrayList<String>>() {
            @Override
            public void accept(ArrayList<String> strings) throws Exception {
                SecretInputView.dismissTcLoading();

//                secretPwd = CertificateUtil.encrypt(etPassword.getText().toString(), publicKey);
                //todo 改为rsa加密
                secretPwd = RSAUtil.encryptByPublicKey(etPassword.getText().toString().trim(), RSAPublicKey);
                Intent intent = new Intent();
                intent.putExtra("encryptList",  strings);
                intent.putExtra("password", secretPwd);
                intent.putExtra("isRawPic", isRawPic);
                setResult(SECRET_IMAGE_RESULT_CODE, intent);
                SecretInputView.dismissTcLoading();
                KeyboardUtils.hideSoftInput(etPassword);
                finish();

            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {
                ToastUtil.showToast(SecretImageActivity.this, ResStringUtil.getString(R.string.wrchatview_image_encryption_fail));
            }
        });

    }


    /**
     * 加密
     *
     * @param url 文件路径
     */
    private void encryptImg(String url) {
        File file = new File(url);
        if (!file.exists() && !file.isFile()) {
            return;
        }
        AESSecretUtil aesSecretUtil = new AESSecretUtil(etPassword.getText().toString().trim());
        //文件转bytes后加密
        byte[] bytes = aesSecretUtil.encrypt(FileIOUtils.readFile2BytesByStream(file));
        //加密后的bytes转文件
        File file1 = new File(ImageUtil.encryptImgPath + FileUtils.getFileName(file));
        try {
            if (!file1.exists()) {
                file1.createNewFile();
            }
            FileIOUtils.writeFileFromBytesByStream(file1.getAbsolutePath(), bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    /**
     * 获取对方用户的公钥
     *
     * @param userId 对方的userId
     */
    private void getUserPublicKey(int userId) {
        OpenEthRequest.getUserEthByImUserId(this, userId, new OpenEthRequest.EthRequestListener() {
            @Override
            public void onSuccess(String ethAddress, String publicKey,String RSAPublicKey) {
                SecretImageActivity.this.ethAddress = ethAddress;
                SecretImageActivity.this.publicKey = publicKey;
                SecretImageActivity.this. RSAPublicKey = RSAPublicKey;
            }

            @Override
            public void onFail(String error) {

            }
        });
    }
}
