package ru.yandex.webmaster.common.http;

import ru.yandex.webmaster.common.WebmasterActionException;
import ru.yandex.webmaster.common.WebmasterExceptionType;

/**
 * @author aherman
 */
public class PrimitiveParameterConverter implements ParameterConverter {
    @Override
    public Object convert(String name, String value, Class<?> toType) {
        if (toType == String.class) {
            return value;
        } else if (toType == Integer.class || toType == Integer.TYPE) {
            return getInteger(name, value);
        } else if (toType == Boolean.class || toType == Boolean.TYPE) {
            return Boolean.valueOf(value);
        } else if (toType == Long.class || toType == Long.TYPE) {
            return getLong(name, value);
        } else if (toType == Float.class || toType == Float.TYPE) {
            return getFloat(name, value);
        } else if (toType == Double.class || toType == Double.TYPE) {
            return getDouble(name, value);
        }
        return null;
    }

    private static Long getLong(String paramName, String valueStr) {
        try {
            return Long.valueOf(valueStr);
        } catch (NumberFormatException e) {
            throw new WebmasterActionException(WebmasterExceptionType.REQUEST__ILLEGAL_PARAMETER_VALUE,
                    "Unable to convert parameter to long: name=" + paramName,
                    "name", paramName, "value", valueStr);
        }
    }

    private static Integer getInteger(String paramName, String valueStr) {
        try {
            return Integer.valueOf(valueStr);
        } catch (NumberFormatException e) {
            throw new WebmasterActionException(WebmasterExceptionType.REQUEST__ILLEGAL_PARAMETER_VALUE,
                    "Unable to convert parameter to int: name=" + paramName,
                    "name", paramName, "value", valueStr);
        }
    }

    private static Float getFloat(String paramName, String valueStr) {
        try {
            return Float.valueOf(valueStr);
        } catch (NumberFormatException e) {
            throw new WebmasterActionException(WebmasterExceptionType.REQUEST__ILLEGAL_PARAMETER_VALUE,
                    "Unable to convert parameter to float: name=" + paramName,
                    "name", paramName, "value", valueStr);
        }
    }

    private static Double getDouble(String paramName, String valueStr) {
        try {
            return Double.valueOf(valueStr);
        } catch (NumberFormatException e) {
            throw new WebmasterActionException(WebmasterExceptionType.REQUEST__ILLEGAL_PARAMETER_VALUE,
                    "Unable to convert parameter to double: name=" + paramName,
                    "name", paramName, "value", valueStr);
        }
    }
}
