package com.efounder.chat.activity;

import android.graphics.drawable.Drawable;
import android.os.Bundle;

import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;
import com.efounder.chat.R;
import com.efounder.chat.http.JFCommonRequestManager;
import com.efounder.chat.utils.AESSecretUtil;
import com.efounder.chat.utils.CommonThreadPoolUtils;
import com.efounder.chat.utils.ImageUtil;
import com.efounder.imageselector.photoview.PhotoView;
import com.efounder.pansoft.chat.input.SecretInputView;
import com.efounder.utils.ResStringUtil;
import com.utilcode.util.FileIOUtils;
import com.utilcode.util.ToastUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;

/**
 * @author wwl
 * 查看加密图片
 */
public class ViewSecretImageActivity extends BaseActivity {

    private static final String TAG = "ViewSecretImageActivity";

    private String url;//加密图片路径
    private String localPath;//消息里的加密图片本地路径
    private boolean isFromLocal;//是否本地消息
    private String password;//解密密码
    private String privateKey;//解密私钥
    private PhotoView photoView;//查看图片缩放

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_wechat_activity_view_secret_image);
        photoView = (PhotoView) findViewById(R.id.photo_view);
        if (getIntent().getExtras() != null) {
            //得到消息中的加密图片地址
            try {
                JSONObject jsonObject = new JSONObject(getIntent().getStringExtra("message"));
                url = jsonObject.optString("url");
                localPath = jsonObject.optString("path");
                isFromLocal = getIntent().getBooleanExtra("fromLocal", false);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            if (url == null) {
                ToastUtils.showShort(R.string.wrchatview_dcryption_failed);
                return;
            }

            //有password则用password解密
            if (getIntent().getExtras().containsKey("password")) {
                password = getIntent().getStringExtra("password");
//                passwordDecrypt();
            }

            //"https://panserver.solarsource.cn/panserver/files/9c648cb9-e2e0-4075-83aa-af90efaf0042/download"
            //取出中间的9c648cb9-e2e0-4075-83aa-af90efaf0042作为文件名
            String fileName = null;
            try {
                fileName = url.substring(0, url.lastIndexOf("/"));
                fileName = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
            } catch (Exception e) {
                e.printStackTrace();
                fileName = System.currentTimeMillis() + "";
            }
            String filePath = ImageUtil.decryptImgPath;
            //本地存在加密文件，则直接解密
            if (isLocalFileExist()) {
                decryptBytes(localPath);
                return;
            }
            //下载加密文件，完成后解密
            downloadImageBytes(url, filePath, fileName);

        }

    }

    /**
     * 判断是否存在本地文件
     *
     * @return true/false
     */
    private boolean isLocalFileExist() {
        if (isFromLocal) {
            File file = new File(localPath);
            if (file.exists()) {
                return true;
            }
        }
        return false;
    }

    /**
     * 下载图片文件为bytes,然后解密
     *
     * @param url
     */
    private void downloadImageBytes(final String url, final String filePath, final String fileName) {
        SecretInputView.showTcLoading(this, ResStringUtil.getString(R.string.wrchatview_down_image_ing));
        JFCommonRequestManager.getInstance()
                .downLoadFile(TAG, url, fileName, filePath, new JFCommonRequestManager.ReqProgressCallBack<File>() {
                    @Override
                    public void onProgress(long total, long current) {

                    }

                    @Override
                    public void onReqSuccess(File file) {
                        SecretInputView.dismissTcLoading();
                        decryptBytes(file.getAbsolutePath());
                    }

                    @Override
                    public void onReqFailed(String errorMsg) {
                        SecretInputView.dismissTcLoading();
                        ToastUtils.showShort(R.string.wrchatview_dcryption_failed);
                    }
                });
    }

    /**
     * 解密bytes并生成本地文件
     */
    private void decryptBytes(final String filePath) {
        SecretInputView.showTcLoading(this, ResStringUtil.getString(R.string.wrchatview_dcryptioning));
        CommonThreadPoolUtils.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    AESSecretUtil aesSecretUtil = new AESSecretUtil(password);
                    //解密bytes
                    final byte[] targetBytes = aesSecretUtil.decrypt(FileIOUtils.readFile2BytesByStream(filePath));
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            //glide直接加载解密后的bytes
                            Glide.with(ViewSecretImageActivity.this).load(targetBytes)
                                    .apply(new RequestOptions()
                                            .skipMemoryCache(true)
                                            .diskCacheStrategy(DiskCacheStrategy.NONE)
                                    )
                                    .listener(new RequestListener<Drawable>() {
                                        @Override
                                        public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                                            SecretInputView.dismissTcLoading();
                                            ToastUtils.showShort(R.string.wrchatview_dcryption_failed);
                                            return false;
                                        }

                                        @Override
                                        public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                                            SecretInputView.dismissTcLoading();
                                            return false;
                                        }
                                    })
                                    .into(photoView);
                        }
                    });

                } catch (Exception e) {
                    SecretInputView.dismissTcLoading();
                    e.printStackTrace();
                    ToastUtils.showShort(R.string.wrchatview_dcryption_failed);
                }
            }
        });

    }
}
