package com.airlock.iam.oauth2.domain.model.client.locales;

import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Locale.LanguageRange;
import lombok.NonNull;

public final class MapBasedLocalizedAttribute implements LocalizedAttribute {
   @NonNull
   private final Optional<String> defaultValue;
   @NonNull
   private final Map<Locale, String> map;

   @Override
   public Optional<String> getValue(Locale locale, LocalizedAttribute.StringPropertyTranslator stringPropertyTranslator) {
      Locale bestMatch = Locale.lookup(LanguageRange.parse(locale.toLanguageTag()), this.map.keySet());
      return bestMatch == null ? this.defaultValue : Optional.ofNullable(this.map.get(bestMatch)).or(() -> this.defaultValue);
   }

   @SuppressFBWarnings(justification = "generated code")
   public MapBasedLocalizedAttribute(@NonNull Optional<String> defaultValue, @NonNull Map<Locale, String> map) {
      if (defaultValue == null) {
         throw new NullPointerException("defaultValue is marked non-null but is null");
      }

      if (map == null) {
         throw new NullPointerException("map is marked non-null but is null");
      }

      this.defaultValue = defaultValue;
      this.map = map;
   }
}
