package chat.rocket.android.helper;

import android.graphics.Typeface;
import android.widget.ImageView;
import com.amulyakhare.textdrawable.TextDrawable;
import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import timber.log.Timber;

/**
 * Helper for rendering user avatar image.
 */
public class Avatar {
  private final String hostname;
  private final String username;

  private static final int[] COLORS = new int[]{
      0xFFF44336, 0xFFE91E63, 0xFF9C27B0, 0xFF673AB7, 0xFF3F51B5, 0xFF2196F3,
      0xFF03A9F4, 0xFF00BCD4, 0xFF009688, 0xFF4CAF50, 0xFF8BC34A, 0xFFCDDC39,
      0xFFFFC107, 0xFFFF9800, 0xFFFF5722, 0xFF795548, 0xFF9E9E9E, 0xFF607D8B
  };

  public Avatar(String hostname, String username) {
    this.hostname = hostname;
    this.username = username;
  }

  private static int getColorForUser(String username) {
    return COLORS[username.length() % COLORS.length];
  }

  private static String getInitialsForUser(String username) {
    String name = username
        .replaceAll("[^A-Za-z0-9]", ".")
        .replaceAll("\\.+", ".")
        .replaceAll("(^\\.)|(\\.$)", "");
    String[] initials = name.split("\\.");
    if (initials.length >= 2) {
      return (firstChar(initials[0]) + firstChar(initials[initials.length - 1])).toUpperCase();
    } else {
      String name2 = name.replaceAll("[^A-Za-z0-9]", "");
      return (name2.length() < 2) ? name2 : name2.substring(0, 2).toUpperCase();
    }
  }

  private static String firstChar(String str) {
    return TextUtils.isEmpty(str) ? "" : str.substring(0, 1);
  }

  private String getImageUrl() {
    //from Rocket.Chat:packages/rocketchat-ui/lib/avatar.coffee
    //REMARK! this is often SVG image! (see: Rocket.Chat:server/startup/avatar.coffee)
    try {
      return "https://" + hostname + "/avatar/" + URLEncoder.encode(username, "UTF-8") + ".jpg";
    } catch (UnsupportedEncodingException exception) {
      Timber.e(exception, "failed to get URL for user: %s", username);
      return null;
    }
  }

  /**
   * render avatar into imageView.
   */
  public void into(final ImageView imageView) {
    Picasso.with(imageView.getContext())
        .load(getImageUrl())
        .into(imageView, new Callback() {
          @Override public void onSuccess() {

          }

          @Override public void onError() {
            textInto(imageView);
          }
        });
  }

  private void textInto(final ImageView imageView) {
    int round = (int) (4 * imageView.getContext().getResources().getDisplayMetrics().density);

    imageView.setImageDrawable(TextDrawable.builder()
        .beginConfig()
        .useFont(Typeface.SANS_SERIF)
        .endConfig()
        .buildRoundRect(getInitialsForUser(username), getColorForUser(username), round));

  }
}

@@ -30,16 +30,48 @@
 elper;%0A%0A
+import android.content.Context;%0A
 import a
@@ -96,16 +96,59 @@
 peface;%0A
+import android.graphics.drawable.Drawable;%0A
 import a
@@ -226,46 +226,8 @@
 le;%0A
-import com.squareup.picasso.Callback;%0A
 impo
@@ -2223,21 +2223,21 @@
     
-Picasso.with(
+Object tag = 
 imag
@@ -2249,145 +2249,153 @@
 .get
-Context())
+Tag();
 %0A    
-    .load(getImageUrl())%0A        .into(imageView, new Callback() %7B%0A          @Override public void onSuccess(
+if (tag != null && tag instanceof String) %7B%0A      String username = (String) tag;%0A      if (this.username.equals(username)
 ) %7B%0A
-%0A
         
   %7D%0A
@@ -2394,168 +2394,303 @@
     
-  %7D%0A%0A
+return;%0A  
     
+%7D%0A
     
-  @Override public void onError() %7B%0A            textInto(imageView);%0A          %7D%0A        %7D);%0A  %7D%0A%0A  private void textInto(final ImageView imageView
+%7D%0A    imageView.setTag(this.username);%0A%0A    final Context context = imageView.getContext();%0A    Picasso.with(context)%0A        .load(getImageUrl())%0A        .placeholder(getTextDrawable(context))%0A        .into(imageView);%0A  %7D%0A%0A  private Drawable getTextDrawable(Context context
 ) %7B%0A
@@ -2716,38 +2716,23 @@
 t) (4 * 
-imageView.getC
+c
 ontext
-()
 .getReso
@@ -2778,35 +2778,15 @@
     
-imageView.setImageDrawable(
+return 
 Text
@@ -2973,18 +2973,16 @@
 , round)
-);%0A
+;
 %0A  %7D%0A%7D%0A

fix user avatar blink.