package ru.yandex.direct.api.v5.ws.validation;

import com.fasterxml.jackson.databind.exc.InvalidFormatException;

import ru.yandex.direct.api.v5.ApiFaultTranslations;
import ru.yandex.direct.i18n.Translatable;

/**
 * Ошибка несоответсвия формата элемента в документе запроса типу элемента в классе бина
 */
public class InvalidFormatApiException extends IncorrectRequestApiException {
    public InvalidFormatApiException(Throwable cause, Translatable detailedMessage) {
        super(cause, detailedMessage);
    }

    public InvalidFormatApiException(Throwable cause, String path, String targetTypeDescription) {
        super(cause, ApiFaultTranslations.INSTANCE.detailedInvalidFormat(path, targetTypeDescription));
    }

    public static InvalidFormatApiException fromJacksonInvalidFormatException(InvalidFormatException ex) {
        String path = JacksonUtil.getMappingExceptionPath(ex);
        Class<?> targetType = ex.getTargetType();

        PathWithArrayPrefix pathWithArrayPrefix = PathWithArrayPrefix.fromPath(ex.getPath());
        boolean problemDirectlyInArray = pathWithArrayPrefix.getInArrayPath().isEmpty();
        if (targetType.isAssignableFrom(Long.class) || targetType.isAssignableFrom(Integer.class)) {
            if (problemDirectlyInArray) {
                return new InvalidFormatApiException(ex,
                        ApiFaultTranslations.INSTANCE.detailedInvalidFormatExpectedIntegerInArray(path));
            } else {
                return new InvalidFormatApiException(ex,
                        ApiFaultTranslations.INSTANCE.detailedInvalidFormatExpectedInteger(path));
            }
        } else if (targetType.isEnum()) {
            if (problemDirectlyInArray) {
                return new InvalidFormatApiException(ex,
                        ApiFaultTranslations.INSTANCE.detailedInvalidFormatExpectedEnumInArray(
                                path, XmlBindUtil.getEnumXmlElements(targetType)));
            } else {
                return new InvalidFormatApiException(ex,
                        ApiFaultTranslations.INSTANCE.detailedInvalidFormatExpectedEnum(
                                path, XmlBindUtil.getEnumXmlElements(targetType)));
            }
        }
        String targetTypeDescription = XmlBindUtil.getXmlTypeDescription(targetType);
        return new InvalidFormatApiException(ex, path, targetTypeDescription);
    }
}
