package com.rv.im;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.WindowManager;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.rv.im.glide.GlideOptions;
import com.rv.im.photopicker.widget.ZoomImageView;
import com.rv.im.util.FileUtil;
import com.rv.im.view.SaveWindow;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import gif.GifDrawable;

/**
 * 单张图片预览
 */
public class SingleImagePreviewActivity extends AppCompatActivity {
    public static final int REQUEST_IMAGE_EDIT = 1;

    private String mImageUri;
    private String mImagePath;
    private String mEditedPath;
    // 是否为阅后即焚类型   当前图片在消息内的位置
    private String delPackedId;

    private ZoomImageView mImageView;
    private Bitmap mBitmap;// 用于 识别图中二维码
    private SaveWindow mSaveWindow;
    private My_BroadcastReceiver my_broadcastReceiver = new My_BroadcastReceiver();

    @SuppressWarnings("unused")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_single_image_preview);

        if (getIntent() != null) {
            mImageUri = getIntent().getStringExtra(Constants.EXTRA_IMAGE_URI);
            mImagePath = getIntent().getStringExtra("image_path");
            boolean isReadDel = getIntent().getBooleanExtra("isReadDel", false);
            if (isReadDel) {
                getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);
            }

            // 这个是阅后即焚消息的 packedId
            delPackedId = getIntent().getStringExtra("DEL_PACKEDID");
        }

        initView();
        register();
    }

    public void doBack() {
        if (!TextUtils.isEmpty(delPackedId)) {
            // 发送广播去更新聊天界面，移除该message
            EventBus.getDefault().post(new MessageEventClickFire("delete", delPackedId));
        }
        finish();
        overridePendingTransition(0, 0);// 关闭过场动画
    }

    @Override
    public void onBackPressed() {
        doBack();
    }

    protected boolean onHomeAsUp() {
        doBack();
        return true;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (my_broadcastReceiver != null) {
            unregisterReceiver(my_broadcastReceiver);
        }
    }

    private void initView() {
//        getSupportActionBar().hide();
        mImageView = findViewById(R.id.image_view);
        if (TextUtils.isEmpty(mImageUri)) {
            Toast.makeText(getApplicationContext(), R.string.image_not_found, Toast.LENGTH_SHORT).show();
            return;
        }

        /*
        加载图片 || 头像
         */
        if (mImageUri.contains("http")) {// 图片 头像的mImageUri为UserId
            boolean isExists = false;
            if (!TextUtils.isEmpty(mImagePath)) {
                File file = new File(mImagePath);
                if (file.exists()) {
                    isExists = true;
                }
            }
            if (isExists) {// 本地加载
                if (mImageUri.endsWith(".gif")) {
                    try {
                        GifDrawable gifDrawable = new GifDrawable(new File(mImagePath));
                        mImageView.setImageDrawable(gifDrawable);
                    } catch (Exception e) {
                        mImageView.setImageResource(R.drawable.image_download_fail_icon);
                        e.printStackTrace();
                    }
                } else {

                    GlideOptions options = GlideOptions.placeholderOf(R.mipmap.default_error).
                            error(R.mipmap.default_error).skipMemoryCache(false);
                    Glide.with(getApplicationContext())
                            .asBitmap()
                            .load(mImagePath)
                            .apply(options)
//                            .apply(RequestOptions.overrideOf(holder.chatPic.getWidth(), holder.chatPic.getHeight()))
                            .into(new SimpleTarget<Bitmap>() {
                                @Override
                                public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                                    mBitmap = resource;
                                    mImageView.setImageBitmap(resource);
                                }

                                @Override
                                public void onLoadFailed(@Nullable Drawable errorDrawable) {
                                    mImageView.setImageResource(R.drawable.image_download_fail_icon);
                                }
                            });
                }
            } else {// 网络加载

                GlideOptions options = GlideOptions.placeholderOf(R.mipmap.default_error).
                        error(R.mipmap.default_error).skipMemoryCache(false).centerCrop().dontAnimate();
                Glide.with(getApplicationContext())
                        .asBitmap()
                        .load(mImageUri)
                        .apply(options)
//                            .apply(RequestOptions.overrideOf(holder.chatPic.getWidth(), holder.chatPic.getHeight()))
                        .into(new SimpleTarget<Bitmap>() {
                            @Override
                            public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                                mBitmap = resource;
                                mImageView.setImageBitmap(resource);
                            }

                            @Override
                            public void onLoadFailed(@Nullable Drawable errorDrawable) {
                                mImageView.setImageResource(R.drawable.image_download_fail_icon);
                            }
                        });
            }
        }
    }

    private void register() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(Constants.OtherBroadcast.singledown);
        filter.addAction(Constants.OtherBroadcast.longpress);
        registerReceiver(my_broadcastReceiver, filter);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case REQUEST_IMAGE_EDIT:
                    mImagePath = mEditedPath;
                    mImageUri = new File(mEditedPath).toURI().toString();

                    GlideOptions options = GlideOptions.placeholderOf(R.mipmap.default_error).
                            error(R.mipmap.default_error).skipMemoryCache(false).centerCrop().dontAnimate();
                    Glide.with(getApplicationContext())
                            .asBitmap()
                            .load(mImagePath)
                            .apply(options)
//                            .apply(RequestOptions.overrideOf(holder.chatPic.getWidth(), holder.chatPic.getHeight()))
                            .into(new SimpleTarget<Bitmap>() {
                                @Override
                                public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                                    mBitmap = resource;
                                    mImageView.setImageBitmap(resource);
                                }

                                @Override
                                public void onLoadFailed(@Nullable Drawable errorDrawable) {
                                    mImageView.setImageResource(R.drawable.image_download_fail_icon);
                                }
                            });

                    // 模拟那个长按，弹出菜单，
                    Intent intent = new Intent(Constants.OtherBroadcast.longpress);
                    sendBroadcast(intent);
                    break;
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    class My_BroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Constants.OtherBroadcast.singledown)) {
                // 轻触屏幕，退出预览
                doBack();
            } else if (intent.getAction().equals(Constants.OtherBroadcast.longpress)) {
                // 长按屏幕，弹出菜单
                mSaveWindow = new SaveWindow(SingleImagePreviewActivity.this, v -> {
                    mSaveWindow.dismiss();
                    int i = v.getId();
                    if (i == R.id.save_image) {
                        if (!TextUtils.isEmpty(delPackedId)) {
                            Toast.makeText(SingleImagePreviewActivity.this, R.string.tip_burn_image_cannot_save, Toast.LENGTH_SHORT).show();
                            return;
                        }
                        if (mImageUri.toLowerCase().endsWith("gif")) {// 保存Gif
                            FileUtil.downImageToGallery(SingleImagePreviewActivity.this, mImagePath);
                        } else {// 保存图片
                            FileUtil.downImageToGallery(SingleImagePreviewActivity.this, mImageUri);
                        }

                    }
//                    else if (i == R.id.edit_image) {
//                        Glide.with(SingleImagePreviewActivity.this)
//                                .load(mImageUri)
//                                .downloadOnly(new SimpleTarget<File>() {
//                                    @Override
//                                    public void onResourceReady(@NonNull File resource, @Nullable Transition<? super File> transition) {
//                                        mEditedPath = FileUtil.createImageFileForEdit().getAbsolutePath();
//                                        IMGEditActivity.startForResult(SingleImagePreviewActivity.this, Uri.fromFile(resource), mEditedPath, REQUEST_IMAGE_EDIT);
//                                    }
//                                });
//                    }
                });
                mSaveWindow.show();
            }
        }
    }
}
