/*
 * Copyright (c) 2014-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */

package com.facebook.stetho.common.android;

import android.content.res.Resources;
import com.facebook.stetho.common.LogUtil;

import javax.annotation.Nonnull;

public class ResourcesUtil {
  private ResourcesUtil() {
  }

  @Nonnull
  public static String getIdStringQuietly(Object idContext, Resources r, int resourceId) {
    try {
      return getIdString(r, resourceId);
    } catch (Resources.NotFoundException e) {
      String idString = "#" + Integer.toHexString(resourceId);
      LogUtil.w("Unknown identifier encountered on " + idContext + ": " + idString);
      return idString;
    }
  }

  public static String getIdString(Resources r, int resourceId) throws Resources.NotFoundException {
    String prefix;
    String prefixSeparator;
    switch (getResourcePackageId(resourceId)) {
      case 0x7f:
        prefix = "";
        prefixSeparator = "";
        break;
      default:
        prefix = r.getResourcePackageName(resourceId);
        prefixSeparator = ":";
        break;
    }

    String typeName = r.getResourceTypeName(resourceId);
    String entryName = r.getResourceEntryName(resourceId);

    StringBuilder sb = new StringBuilder(
        1 + prefix.length() + prefixSeparator.length() +
            typeName.length() + 1 + entryName.length());
    sb.append("@");
    sb.append(prefix);
    sb.append(prefixSeparator);
    sb.append(typeName);
    sb.append("/");
    sb.append(entryName);

    return sb.toString();
  }

  private static int getResourcePackageId(int id) {
    return (id >>> 24) & 0xff;
  }
}

@@ -461,16 +461,50 @@
 Nonnull;
+%0Aimport javax.annotation.Nullable;
 %0A%0Apublic
@@ -629,16 +629,26 @@
 Context,
+ @Nullable
  Resourc
@@ -796,27 +796,21 @@
 g = 
-%22#%22 + Integer.toHex
+getFallbackId
 Stri
@@ -979,16 +979,26 @@
 dString(
+@Nullable 
 Resource
@@ -1017,16 +1017,22 @@
 ourceId)
+%0A     
  throws 
@@ -1061,16 +1061,90 @@
 ption %7B%0A
+    if (r == null) %7B%0A      return getFallbackIdString(resourceId);%0A    %7D%0A%0A
     Stri
@@ -1852,24 +1852,24 @@
 ntryName);%0A%0A
-
     return s
@@ -1887,16 +1887,133 @@
 );%0A  %7D%0A%0A
+  private static String getFallbackIdString(int resourceId) %7B%0A    return %22#%22 + Integer.toHexString(resourceId);%0A  %7D%0A%0A
   privat

Fix NPE crash in ResourcesUtil.getIdString()