package com.braintreeocc.validators.impl;

import com.braintree.hybris.data.ws.BraintreeCreditCardPaymentDetailsWsDTO;
import com.braintreeocc.validators.BrainTreeValidator;
import de.hybris.platform.commercewebservicescommons.dto.order.PaymentDetailsWsDTO;
import org.apache.commons.lang.StringUtils;
import org.springframework.util.Assert;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import java.util.Calendar;

public class BraintreeCreditCardPaymentResponseValidator implements BrainTreeValidator {

    private static final String FIELD_REQUIRED_MESSAGE_ID = "field.required";

    private Validator creditCardDataValidator;
    private Validator paymentAddressValidator;

    @Override
    public boolean supports(Class aClass) {
        return BraintreeCreditCardPaymentDetailsWsDTO.class.isAssignableFrom(aClass);
    }

    @Override
    public void validate(Object target, Errors errors) {

        final BraintreeCreditCardPaymentDetailsWsDTO creditCardPaymentDetails = (BraintreeCreditCardPaymentDetailsWsDTO) target;

        validateCreditCardPaymentDetails(creditCardPaymentDetails, errors);

        Assert.notNull(creditCardPaymentDetails.getTokenizedCardData(), "Tokenized credit card data must not be null");
        validate(creditCardPaymentDetails.getTokenizedCardData(), "tokenizedCardData", creditCardDataValidator);
    }

    private void validateCreditCardPaymentDetails(final Object target, Errors errors) {

        final PaymentDetailsWsDTO paymentDetails = (PaymentDetailsWsDTO) target;

        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "accountHolderName", FIELD_REQUIRED_MESSAGE_ID);

        paymentAddressValidator.validate(paymentDetails, errors);
    }

    public void setCreditCardDataValidator(Validator creditCardDataValidator) {
        this.creditCardDataValidator = creditCardDataValidator;
    }

    public void setPaymentAddressValidator(final Validator paymentAddressValidator) {
        this.paymentAddressValidator = paymentAddressValidator;
    }
}
