package de.accso.flexinale.besucherportal.api_contract.event;

import de.accso.flexinale.common.api.event.Event;
import de.accso.flexinale.common.shared_kernel.FlexinaleIllegalArgumentException;

import java.lang.reflect.Field;

public final class ReflectionHelper {
    public static void setField(final Class<?> eventType, final Event event, final String fieldName, final Object fieldValue,
                         boolean includeDerivedFieldsFromSuperClasses) throws IllegalAccessException {
        if (eventType.equals(Object.class)) {
            throw new FlexinaleIllegalArgumentException("event hierarchy does not have a field " + fieldName);
        }
        try {
            Field field = (includeDerivedFieldsFromSuperClasses)
                    ? eventType.getField(fieldName)
                    : eventType.getDeclaredField(fieldName);
            field.setAccessible(true);
            field.set(event, fieldValue);
        }
        catch (NoSuchFieldException nosfex) {
            setField(eventType.getSuperclass(), event, fieldName, fieldValue, includeDerivedFieldsFromSuperClasses);
        }
    }
}
