package ru.yandex.webmaster3.storage.util.clickhouse2.condition;

/**
 * @author avhaliullin
 */
public abstract class ConditionFieldExtractor<T> {
    public <R> R extract(T object, String fieldName, Class<R> clazz) {
        Object res = extractRaw(object, fieldName);
        if (res == null) {
            return null;
        }
        if (clazz.isAssignableFrom(res.getClass())) {
            return (R) res;
        }
        throw new IllegalArgumentException("Expected " + clazz + " but found " + res + " for field " + fieldName + " of " + object);
    }

    protected abstract Object extractRaw(T object, String fieldName);

    public static <T> ConditionFieldExtractor<T> identity(Class<T> clazz) {
        return new ConditionFieldExtractor<T>() {
            @Override
            protected Object extractRaw(T object, String fieldName) {
                return object;
            }
        };
    }
}
