/**
 * Copyright (C) 2013-2014 EaseMob Technologies. All rights reserved.
 * <p/>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.easemob.veckit;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;



import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.easemob.veckit.ui.widget.photoview.PhotoView;
import com.easemob.veckit.utils.CloudCallbackUtils;
import com.hyphenate.chat.ChatClient;
import com.hyphenate.chat.EMImageMessageBody;
import com.hyphenate.chat.Message;
import com.hyphenate.chat.VecChatManager;
import com.hyphenate.helpdesk.callback.Callback;
import com.hyphenate.helpdesk.easeui.util.StatusBarUtils;
import com.hyphenate.util.EMLog;
import com.hyphenate.util.ImageUtils;
import com.hyphenate.util.UriUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * 下载显示大图
 */
public class ShowBigImageActivity extends Activity {
    private static final String TAG = "ShowBigImage";
    private ProgressDialog pd;
    private PhotoView image;
    private int default_res = R.drawable.hd_default_image;
    private String filename;
    private Bitmap bitmap;
    private boolean isDownloaded;

    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StatusBarUtils.setImmersiveStatusBar(this, false);
        setContentView(R.layout.vec_activity_show_big_image);

        image = (PhotoView) findViewById(R.id.image);
        default_res = getIntent().getIntExtra("default_image", R.drawable.hd_default_avatar);
        Uri uri = getIntent().getParcelableExtra("uri");
        filename = getIntent().getExtras().getString("filename");
        String msgId = getIntent().getExtras().getString("messageId");
        EMLog.d(TAG, "show big msgId:" + msgId );

        if (UriUtils.isFileExistByUri(this, uri)) {
            Glide.with(this).load(uri).into(image);
        } else if(msgId != null) {
            downloadImage(msgId);
        }else {
            image.setImageResource(default_res);
        }

        image.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                setResult(-1, null);
                finish();
            }
        });

        findViewById(R.id.closeItv).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    /**
     * download image
     *
     * @param msgId
     */
    @SuppressLint("NewApi")
    private void downloadImage(final String msgId) {
        EMLog.e(TAG, "download with messageId: " + msgId);
        String str1 = getResources().getString(R.string.Download_the_pictures);
        pd = new ProgressDialog(this);
        pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        pd.setCanceledOnTouchOutside(false);
        pd.setMessage(str1);
        pd.show();

        final Message msg = VecChatManager.getInstance().getVecConversation().getMessage(msgId);

        if (msg == null){
            pd.dismiss();
            image.setImageResource(default_res);
            return;
        }
        final Callback callback = new Callback() {
            public void onSuccess() {
                EMLog.e(TAG, "onSuccess" );
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (!isFinishing() && !isDestroyed()) {
                            if (pd != null) {
                                pd.dismiss();
                            }
                            isDownloaded = true;

                            EMImageMessageBody body = (EMImageMessageBody) msg.getBody();
                            saveToPic(getApplicationContext(), body.getLocalUrl(), body.getFileName(), body.getWidth());


                            Uri localUrlUri = ((EMImageMessageBody) msg.getBody()).getLocalUri();
                            Glide.with(ShowBigImageActivity.this)
                                    .load(localUrlUri)
                                    .apply(new RequestOptions().error(default_res))
                                    .into(image);
                        }
                    }
                });
            }

            public void onError(final int error, String message) {
                EMLog.e(TAG, "offline file transfer error:" + message);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (ShowBigImageActivity.this.isFinishing() || ShowBigImageActivity.this.isDestroyed()) {
                            return;
                        }
                        image.setImageResource(default_res);
                        pd.dismiss();
                    }
                });
            }

            public void onProgress(final int progress, String status) {
                EMLog.d(TAG, "Progress: " + progress);
                final String str2 = getResources().getString(R.string.Download_the_pictures_new);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (ShowBigImageActivity.this.isFinishing() || ShowBigImageActivity.this.isDestroyed()) {
                            return;
                        }
                        pd.setMessage(str2 + progress + "%");
                    }
                });
            }
        };


        msg.setMessageStatusCallback(callback);
        ChatClient.getInstance().vecChatManager().downloadAttachment(msg);
    }

    @Override
    public void onBackPressed() {
        if (isDownloaded){
            setResult(RESULT_OK, null);
        }else {
            setResult(-1, null);
        }
        finish();
    }

    @Override
    protected void onStop() {
        super.onStop();
        CloudCallbackUtils.newCloudCallbackUtils().notifyMark(false);
    }


    void saveToPic(Context context, String uri, String fileName, int width){
        try{
            BitmapFactory.Options var1 = new BitmapFactory.Options();
            var1.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(uri, var1);
            int width1 = var1.outWidth;
            int height = var1.outHeight;
            fileSaveToPublic(context, ImageUtils.decodeScaleImage(uri, width1, height), fileName, uri);
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    public static void fileSaveToPublic(Context context, Bitmap bitmap, String fileName, String path) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            //Android 10及以上版本
            //设置路径 Pictures/
            String folder = Environment.DIRECTORY_PICTURES;
            //设置保存参数到ContentValues中
            ContentValues values = new ContentValues();
            //设置图片名称
            values.put(MediaStore.Images.Media.DISPLAY_NAME, fileName);
            //设置图片格式
            values.put(MediaStore.Images.Media.MIME_TYPE, "image/png");
            //设置图片路径
            values.put(MediaStore.Images.Media.RELATIVE_PATH, folder);
            //执行insert操作，向系统文件夹中添加文件
            //EXTERNAL_CONTENT_URI代表外部存储器，该值不变
            Uri uri = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            OutputStream os = null;
            try {
                if (uri != null) {
                    //若生成了uri，则表示该文件添加成功
                    //使用流将内容写入该uri中即可
                    os = context.getContentResolver().openOutputStream(uri);
                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);
                    os.flush();
                }
            } catch (IOException e) {
                e.printStackTrace();

            } finally {
                if (os != null) {
                    try {
                        os.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (bitmap != null){
                    bitmap.recycle();
                }
            }
            MediaScannerConnection.scanFile(context,
                    new String[]{path},
                    null, null);
        }else {
            File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
            // 创建文件夹
            if (!file.exists()){
                file.mkdirs();
            }
            // 文件名称
            File file_url = new File(file, fileName);
            if (file_url.exists()){
                file_url.delete();
            }

            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(file_url);
                // 通过io流的方式来压缩保存图片
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
                fos.flush();
                fos.close();
                // 保存图片后发送广播通知更新数据库
                MediaScannerConnection.scanFile(context,
                        new String[]{file_url.toString()},
                        null, null);
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                if (fos != null) {
                    try {
                        fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (bitmap != null){
                    bitmap.recycle();
                }
            }
        }
    }
}
