package ru.yandex.webmaster.common.http;

import java.lang.reflect.Field;

import ru.yandex.misc.enums.EnumResolver;
import ru.yandex.webmaster.common.WebmasterActionException;
import ru.yandex.webmaster.common.WebmasterExceptionType;

/**
 * @author aherman
 */
public class EnumParameterConverter implements ParameterConverter {
    @Override
    public Object convert(String name, String value, Class<?> toType) {
        if (toType.isEnum()) {
            return getEnum(name, value, toType);
        }
        return null;
    }

    private static Object getEnum(String paramName, String valueStr, Class<?> desiredClass) {
        try {
            Field r = desiredClass.getField("R");
            if (EnumResolver.class.isAssignableFrom(r.getType())) {
                EnumResolver<?> enumResolver = (EnumResolver) r.get(null);
                return enumResolver.valueOfOrUnknown(valueStr);
            }
        } catch (NoSuchFieldException | IllegalAccessException e) {
            // Resolver is not found. Try to find exact enum value.
        }

        Enum[] enumConstants = (Enum[]) desiredClass.getEnumConstants();
        for (Enum enumConstant : enumConstants) {
            if (enumConstant.name().equalsIgnoreCase(valueStr)) {
                return enumConstant;
            }
        }
        throw new WebmasterActionException(WebmasterExceptionType.REQUEST__ILLEGAL_PARAMETER_VALUE,
                "Unable to convert value to enum: name=" + paramName,
                "name", paramName, "value", valueStr);
    }
}
