package gov.va.med.esr.voa.validator;

import gov.va.med.esr.common.model.lookup.PhoneType;
import gov.va.med.esr.voa.common.ErrorCode;
import gov.va.med.esr.voa.util.ServiceUtils;
import gov.va.med.esr.voa.webservice.PhoneInfo;
import gov.va.med.fw.service.AbstractComponent;

import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

/**
 * Validate phone info
 */
public class PhoneInfoValidator extends AbstractComponent implements Validator {

	@SuppressWarnings("rawtypes")
	@Override
	public boolean supports(Class clazz) {
		return PhoneInfo.class.equals(clazz);
	}

	@Override
	public void validate(Object target, Errors errors) {
		logger.debug("Phone info validation...");

		if (target != null) {
			PhoneInfo phoneInfo = (PhoneInfo) target;

			String phoneNumber = phoneInfo.getPhoneNumber();
			String type = phoneInfo.getType();

			// for home phone
			if (PhoneType.CODE_HOME.getCode().equalsIgnoreCase(type)) {
				if (!ServiceUtils.validatePhone(phoneNumber)) {
					errors.reject(ErrorCode.VOA_0037,
							"Invalid Veteran Home Phone Number.");
					logger.debug("Invalid veteran home phone number. "
							+ phoneNumber);
				}
			} else if (PhoneType.CODE_MOBILE.getCode().equalsIgnoreCase(type)) {
				// for cell phone
				if (!ServiceUtils.validatePhone(phoneNumber)) {
					errors.reject(ErrorCode.VOA_0038,
							"Invalid Veteran cellular phone Number.");
					logger.debug("Invalid veteran cellular phone number. "
							+ phoneNumber);
				}
			}
		}

		logger.debug("Phone info validation - Done.");
	}

}
