001package com.mrivanplays.annotationconfig.core.utils;
002
003import java.util.ArrayList;
004import java.util.List;
005import java.util.Map;
006
007/**
008 * A utility class for interacting with {@link Map Maps} and combining them, putting values at the
009 * right place. They're self-explanatory and they won't be documented. If you are going to use them,
010 * do not expect support.
011 *
012 * @author MrIvanPlays
013 * @since 2.1.0
014 */
015public final class MapUtils {
016
017  public static String getLastKey(Map<String, Object> map) {
018    List<String> keys = new ArrayList<>(map.keySet());
019    return keys.get(keys.size() - 1);
020  }
021
022  @Deprecated
023  public static Map<String, Object> getLastMap(Map<String, Object> map) {
024    Map<String, Object> ret = map;
025    for (Map.Entry<String, Object> entry : map.entrySet()) {
026      Object val = entry.getValue();
027      if (!(val instanceof Map)) {
028        break;
029      }
030      ret = getLastMap((Map<String, Object>) val);
031    }
032    return ret;
033  }
034
035  public static Map<String, Object> getLastCommonMap(
036      Map<String, Object> map1, Map<String, Object> map2) {
037    Map<String, Object> ret = map2;
038    for (Map.Entry<String, Object> entry : map1.entrySet()) {
039      if (map2.containsKey(entry.getKey())) {
040        Object val = map2.get(entry.getKey());
041        if (val instanceof Map) {
042          ret = (Map<String, Object>) val;
043        }
044      }
045    }
046    return ret;
047  }
048
049  public static void populateFirst(Map<String, Object> map1, Map<String, Object> map2) {
050    Map<String, Object> lastCommonMap1 = getLastCommonMap(map1, map2);
051    Map<String, Object> lastCommonMap2 = getLastCommonMap(map2, map1);
052    String lastKeyMap1;
053    if (lastCommonMap1.size() == 1) {
054      lastKeyMap1 = lastCommonMap1.keySet().stream().findFirst().get();
055    } else {
056      lastKeyMap1 = getLastKey(lastCommonMap1);
057    }
058    if (lastCommonMap2.containsKey(lastKeyMap1)) {
059      Object contained = lastCommonMap2.get(lastKeyMap1);
060      if (!(contained instanceof Map)) {
061        throw new IllegalArgumentException("Something's wrong here. Check your annotated config.");
062      }
063      Map<String, Object> mContained = (Map<String, Object>) contained;
064      Map<String, Object> m1 = (Map<String, Object>) lastCommonMap1.get(lastKeyMap1);
065      mContained.putAll(m1);
066    } else {
067      lastCommonMap2.putAll(lastCommonMap1);
068    }
069  }
070
071  private MapUtils() {
072    throw new IllegalArgumentException("Instantiation of utility-type class.");
073  }
074}