class AvdWizardUtils {

  @VisibleForTesting
  static void convertWebpSkinToPng(@NotNull FileOp fop, @NotNull File dest, @NotNull File resourcePath) throws IOException {
    File[] files = fop.listFiles(resourcePath);
    Map<String,String> renameMap = Maps.newHashMap();
    File skinFile = null;
    for (File src : files) {
      String name = src.getName();
      if (name.equals(FN_SKIN_LAYOUT)) {
        skinFile = src;
        continue;
      }

      if (name.endsWith(DOT_WEBP)) {
        // Convert WEBP to PNG until emulator supports it
        try (InputStream inputStream = new BufferedInputStream(fop.newFileInputStream(src))) {
          BufferedImage icon = ImageIO.read(inputStream);
          if (icon != null) {
            File target = new File(dest, name.substring(0, name.length() - DOT_WEBP.length()) + DOT_PNG);
            try (BufferedOutputStream outputStream = new BufferedOutputStream(fop.newFileOutputStream(target))) {
              ImageIO.write(icon, "PNG", outputStream);
              renameMap.put(name, target.getName());
              continue;
            }
          }
        }
      }

      // Normal copy: either the file is not a webp or skin file (for example, some skins such as the
      // wear ones are not in webp format), or it's a webp file where we couldn't
      // (a) decode the webp file (for example if there's a problem loading the native library doing webp
      // decoding, or (b) there was an I/O error writing the PNG file. In that case we'll leave the file in
      // webp format (current emulators support it.)
      File target = new File(dest, name);
      if (fop.isFile(src) && !fop.exists(target)) {
        fop.copyFile(src, target);
      }
    }

    if (skinFile != null) {
      // Replace skin paths
      try (InputStream inputStream = new BufferedInputStream(fop.newFileInputStream(skinFile))) {
        File target = new File(dest, skinFile.getName());
        try (BufferedOutputStream outputStream = new BufferedOutputStream(fop.newFileOutputStream(target))) {
          byte[] bytes = ByteStreams.toByteArray(inputStream);
          String layout = new String(bytes, Charsets.UTF_8);
          for (Map.Entry<String, String> entry : renameMap.entrySet()) {
            layout = layout.replace(entry.getKey(), entry.getValue());
          }
          outputStream.write(layout.getBytes(Charsets.UTF_8));
        }
      }
    }
  }

}