
package de.ivu.elect.util;

import java.util.Optional;

public class ClassUtil {

  private ClassUtil() {
    super();
  }

  public static boolean isEnumClass(Class< ? > clazz) {
    return clazz != null && (clazz.isEnum() || clazz.isAnonymousClass() && clazz.getEnclosingClass() != null && clazz.getEnclosingClass().isEnum());
  }

  public static Class< ? > getEnumClass(Enum< ? > value) {
    if (value != null) {
      return getClass(value.getClass()).filter(ClassUtil::isEnumClass).orElse(null);
    }

    return null;
  }

  public static String getClassName(Object value) {
    if (value != null) {
      return getClassName(value.getClass());
    }

    return "";
  }

  public static String getClassName(Class< ? > clazz) {
    return getClass(clazz).map(Class::getName).orElse("");
  }

  public static String getClassSimpleName(Object value) {
    if (value != null) {
      return getClassSimpleName(value.getClass());
    }

    return "";
  }

  public static String getClassSimpleName(Class< ? > clazz) {
    return getClass(clazz).map(Class::getSimpleName).orElse("");
  }

  private static Optional<Class< ? >> getClass(Class< ? > candidate) {
    Class< ? > result = candidate;

    if (result != null) {
      if (result.isAnonymousClass()) {
        result = result.getSuperclass();
      }
    }

    return Optional.ofNullable(result);
  }
}
