// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij;

import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.SystemInfoRt;
import com.intellij.util.text.OrdinalFormat;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.text.MessageFormat;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

/**
 * @author yole
 */
public abstract class BundleBase {
  public static final char MNEMONIC = 0x1B;
  public static final String MNEMONIC_STRING = Character.toString(MNEMONIC);
  public static final String L10N_MARKER = "🔅";
  public static final boolean SHOW_LOCALIZED_MESSAGES = Boolean.getBoolean("idea.l10n");
  private static final Logger LOG = Logger.getInstance(BundleBase.class);

  private static boolean assertOnMissedKeys = false;

  public static void assertOnMissedKeys(boolean doAssert) {
    assertOnMissedKeys = doAssert;
  }

  @NotNull
  public static String message(@NotNull ResourceBundle bundle, @NotNull String key, @NotNull Object... params) {
    return messageOrDefault(bundle, key, null, params);
  }

  public static String messageOrDefault(@Nullable ResourceBundle bundle,
                                        @NotNull String key,
                                        @Nullable String defaultValue,
                                        @NotNull Object... params) {
    if (bundle == null) return defaultValue;

    boolean resourceFound = true;
    
    String value;
    try {
      value = bundle.getString(key);
    }
    catch (MissingResourceException e) {
      resourceFound = false;
      value = useDefaultValue(bundle, key, defaultValue);
    }

    String result = postprocessValue(bundle, value, params);

    if (SHOW_LOCALIZED_MESSAGES && resourceFound) {
      return appendLocalizationMarker(result);
    }
    return result;
  }

  private static final String[] SUFFIXES = {"</body></html>", "</html>"};

  @NotNull
  protected static String appendLocalizationMarker(@NotNull String result) {
    for (String suffix : SUFFIXES) {
      if (result.endsWith(suffix)) return result.substring(0, result.length() - suffix.length()) + L10N_MARKER + suffix;
    }
    return result + L10N_MARKER;
  }

  @NotNull
  static String useDefaultValue(@Nullable ResourceBundle bundle, @NotNull String key, @Nullable String defaultValue) {
    if (defaultValue != null) {
      return defaultValue;
    }

    if (assertOnMissedKeys) {
      LOG.error("'" + key + "' is not found in " + bundle);
    }
    return "!" + key + "!";
  }

  @Nullable
  static String postprocessValue(@NotNull ResourceBundle bundle, @Nullable String value, @NotNull Object[] params) {
    value = replaceMnemonicAmpersand(value);

    if (params.length > 0 && value.indexOf('{') >= 0) {
      Locale locale = bundle.getLocale();
      try {
        MessageFormat format = locale != null ? new MessageFormat(value, locale) : new MessageFormat(value);
        OrdinalFormat.apply(format);
        value = format.format(params);
      }
      catch (IllegalArgumentException e) {
        value = "!invalid format: `" + value + "`!";
      }
    }

    return value;
  }

  @NotNull
  public static String format(@NotNull String value, @NotNull Object... params) {
    return params.length > 0 && value.indexOf('{') >= 0 ? MessageFormat.format(value, params) : value;
  }

  @Contract("null -> null")
  public static String replaceMnemonicAmpersand(@Nullable String value) {
    if (value == null || value.indexOf('&') < 0) {
      return value;
    }

    StringBuilder builder = new StringBuilder();
    boolean macMnemonic = value.contains("&&");
    int i = 0;
    while (i < value.length()) {
      char c = value.charAt(i);
      if (c == '\\') {
        if (i < value.length() - 1 && value.charAt(i + 1) == '&') {
          builder.append('&');
          i++;
        }
        else {
          builder.append(c);
        }
      }
      else if (c == '&') {
        if (i < value.length() - 1 && value.charAt(i + 1) == '&') {
          if (SystemInfoRt.isMac) {
            builder.append(MNEMONIC);
          }
          i++;
        }
        else if (!SystemInfoRt.isMac || !macMnemonic) {
          builder.append(MNEMONIC);
        }
      }
      else {
        builder.append(c);
      }
      i++;
    }
    return builder.toString();
  }
}
@@ -738,29 +738,30 @@
 EMONIC);%0A  p
-ublic
+rivate
  static fina
@@ -995,24 +995,16 @@
 ssedKeys
- = false
 ;%0A%0A  pub
@@ -1192,16 +1192,23 @@
 ing key,
+ Object
  @NotNul
@@ -1201,38 +1201,32 @@
 Object @NotNull 
-Object
 ... params) %7B%0A  
@@ -1521,32 +1521,39 @@
                 
+Object 
 @NotNull Object.
@@ -1537,38 +1537,32 @@
 Object @NotNull 
-Object
 ... params) %7B%0A  
@@ -2735,23 +2735,22 @@
  %7D%0A%0A  @N
+otN
 ull
-able
 %0A  stati
@@ -2805,31 +2805,30 @@
 e bundle, @N
+otN
 ull
-able
  String valu
@@ -2821,32 +2821,39 @@
 ll String value,
+ Object
  @NotNull Object
@@ -2850,16 +2850,11 @@
 ull 
-Object%5B%5D
+...
  par
@@ -3406,16 +3406,23 @@
 g value,
+ Object
  @NotNul
@@ -3423,22 +3423,16 @@
 NotNull 
-Object
 ... para
@@ -3545,16 +3545,16 @@
 e;%0A  %7D%0A%0A
-
   @Contr
@@ -3566,16 +3566,32 @@
 null -%3E 
+null; !null -%3E !
 null%22)%0A 

fix nullability of params