package com.airlock.iam.common.infrastructure.json;

import com.airlock.iam.base.misc.json.JsonCoding;
import java.util.HashMap;
import java.util.Map;

final class ResourceBundleSerializer {
   public static String serialize(Map<String, String> bundleMap) {
      Map<String, Object> jsonObject = new HashMap<>();
      bundleMap.forEach((key, value) -> computeFromBundleEntry(jsonObject, key, value));
      return JsonCoding.toJson(jsonObject);
   }

   private static void computeFromBundleEntry(Map<String, Object> json, String key, String value) {
      if (!key.contains(".")) {
         json.put(key, value);
      } else {
         String currentKey = firstKey(key);
         if (currentKey != null) {
            String nextKey = key.substring(currentKey.length() + 1);
            Map<String, Object> childJson = computeJsonObject(json, currentKey);
            computeFromBundleEntry(childJson, nextKey, value);
            json.put(currentKey, childJson);
         }
      }
   }

   private static String firstKey(String fullKey) {
      String[] splittedKey = fullKey.split("\\.");
      return splittedKey.length != 0 ? splittedKey[0] : fullKey;
   }

   private static Map<String, Object> computeJsonObject(Map<String, Object> parent, String key) {
      if (!(parent.get(key) instanceof Map)) {
         parent.put(key, new HashMap());
      }

      return (Map<String, Object>)parent.computeIfAbsent(key, k -> new HashMap());
   }

   private ResourceBundleSerializer() {
      throw new AssertionError();
   }
}
