package me.ykrank.s1next.binding;

import android.content.Context;
import android.databinding.BindingAdapter;
import android.support.v7.widget.PopupMenu;
import android.view.MenuItem;
import android.view.View;

import com.bumptech.glide.DrawableRequestBuilder;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;

import me.ykrank.s1next.App;
import me.ykrank.s1next.R;
import me.ykrank.s1next.data.User;
import me.ykrank.s1next.data.api.Api;
import me.ykrank.s1next.data.api.model.Post;
import me.ykrank.s1next.data.event.BlackListAddEvent;
import me.ykrank.s1next.data.pref.DownloadPreferencesManager;
import me.ykrank.s1next.view.activity.GalleryActivity;
import me.ykrank.s1next.widget.BezelImageView;
import me.ykrank.s1next.widget.EventBus;

public final class BezelImageViewBindingAdapter {

    private BezelImageViewBindingAdapter() {
    }

    /**
     * Show default avatar if user hasn't logged in,
     * otherwise show user's avatar.
     */
    @BindingAdapter("user")
    public static void loadUserAvatar(BezelImageView bezelImageView, User user) {
        Context context = bezelImageView.getContext();
        DownloadPreferencesManager downloadPreferencesManager = App.getPrefComponent(context)
                .getDownloadPreferencesManager();
        if (user.isLogged()) {
            // setup user's avatar
            Glide.with(context)
                    .load(Api.getAvatarMediumUrl(user.getUid()))
                    .error(R.drawable.ic_drawer_avatar_placeholder)
                    .signature(downloadPreferencesManager.getAvatarCacheInvalidationIntervalSignature())
                    .transform(new CenterCrop(Glide.get(context).getBitmapPool()))
                    .into(bezelImageView);
        } else {
            // setup default avatar
            Glide.with(context)
                    .load(R.drawable.ic_drawer_avatar_placeholder)
                    .signature(downloadPreferencesManager.getAvatarCacheInvalidationIntervalSignature())
                    .transform(new CenterCrop(Glide.get(context).getBitmapPool()))
                    .into(bezelImageView);
        }
    }

    @BindingAdapter({"eventBus", "avatarDrawableRequestBuilder", "downloadPreferencesManager", "post"})
    public static void loadAuthorAvatar(BezelImageView bezelImageView, EventBus eventBus,
                                        DrawableRequestBuilder<String> avatarDrawableRequestBuilder,
                                        DownloadPreferencesManager downloadPreferencesManager,
                                        Post post) {
        // whether need to download avatars
        // depends on settings and Wi-Fi status
        if (downloadPreferencesManager.isAvatarsDownload()) {
            bezelImageView.setVisibility(View.VISIBLE);

            String url = downloadPreferencesManager.isHighResolutionAvatarsDownload()
                    ? Api.getAvatarMediumUrl(post.getAuthorId())
                    : Api.getAvatarSmallUrl(post.getAuthorId());
            // show user's avatar
            avatarDrawableRequestBuilder.signature(
                    downloadPreferencesManager.getAvatarCacheInvalidationIntervalSignature())
                    .load(url)
                    .into(bezelImageView);

            //点击显示头像大图
            bezelImageView.setOnClickListener(v -> {
                GalleryActivity.startGalleryActivity(v.getContext(), Api.getAvatarBigUrl(post.getAuthorId())
                        , url);
            });
            //长按显示抹布菜单
            bezelImageView.setOnLongClickListener((View v) -> {
                PopupMenu popup = new PopupMenu(bezelImageView.getContext(), v);
                popup.setOnMenuItemClickListener((MenuItem menuitem) -> {
                    switch (menuitem.getItemId()) {
                        case R.id.menu_popup_blacklist:
                            if (menuitem.getTitle().equals(bezelImageView.getContext().getString(R.string.menu_blacklist_remove))) {
                                eventBus.post(new BlackListAddEvent(Integer.valueOf(post.getAuthorId()),
                                        post.getAuthorName(), false));
                            } else {
                                eventBus.post(new BlackListAddEvent(Integer.valueOf(post.getAuthorId()),
                                        post.getAuthorName(), true));
                            }
                            return true;
                        default:
                            return false;
                    }
                });
                popup.inflate(R.menu.popup_blacklist);
                if (post.isHide()) {
                    popup.getMenu().findItem(R.id.menu_popup_blacklist).setTitle(R.string.menu_blacklist_remove);
                }
                popup.show();
                return true;
            });
        } else {
            bezelImageView.setVisibility(View.GONE);
        }
    }

    @BindingAdapter("uid")
    public static void loadPmAvatar(BezelImageView bezelImageView, String uid) {
        Context context = bezelImageView.getContext();
        DownloadPreferencesManager downloadPreferencesManager = App.getPrefComponent(context)
                .getDownloadPreferencesManager();
        Glide.with(context)
                .load(Api.getAvatarMediumUrl(uid))
                .error(R.drawable.ic_drawer_avatar_placeholder)
                .signature(downloadPreferencesManager.getAvatarCacheInvalidationIntervalSignature())
                .transform(new CenterCrop(Glide.get(context).getBitmapPool()))
                .into(bezelImageView);

    }
}

@@ -28,16 +28,82 @@
 nding;%0A%0A
+import android.annotation.TargetApi;%0Aimport android.app.Activity;%0A
 import a
@@ -126,16 +126,16 @@
 ontext;%0A
-
 import a
@@ -165,24 +165,49 @@
 ingAdapter;%0A
+import android.os.Build;%0A
 import andro
@@ -1238,32 +1238,273 @@
 w.getContext();%0A
+        if (context instanceof Activity) %7B%0A            //in device from 4.2 to 4.3, destroyed activity will cause glide error%0A            if (isActivityDestroyedForGlide((Activity) context)) %7B%0A                return;%0A            %7D%0A        %7D%0A
         Download
@@ -2468,32 +2468,32 @@
 ezelImageView);%0A
-
         %7D%0A    %7D%0A
@@ -2485,32 +2485,376 @@
        %7D%0A    %7D%0A%0A
+    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)%0A    private static boolean isActivityDestroyedForGlide(Activity activity) %7B%0A        if (Build.VERSION.SDK_INT %3E= Build.VERSION_CODES.JELLY_BEAN_MR1 && activity.isDestroyed()) %7B%0A            //start a load for a destroyed activity%0A            return true;%0A        %7D%0A        return false;%0A    %7D%0A%0A
     @BindingAdap

修复android 4.2,4.3上glide加载头像导致的一个crash