package gov.va.vss.web;

import java.time.LocalDate;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;

import gov.va.vss.model.volunteer.Volunteer;
import gov.va.vss.util.ValidationUtil;
import gov.va.vss.util.context.SessionUtil;

@Component
public class VolunteerValidator extends AbstractAppValidator<VolunteerCommand> {

	@Override
	public void doExtraValidations(VolunteerCommand command, Errors errors) {
		Volunteer volunteer = command.getVolunteer();

		// for example: CPB

		// if (volunteer.getCurrentInactivationDate() != null
		// && DateTimeComparator.getInstance().compare(
		// volunteer.getCurrentActivationDate(),
		// volunteer.getCurrentInactivationDate()) > 0) {
		// errors.rejectValue("currentInactivationDate",
		// "currentInactivationDate.errors.invalidInactivationDate",
		// "The inactivation date must be later than the activation date");
		// }

		// or:

		// ValidationUtils.rejectIfEmpty(errors, field, errorCode, errorArgs,
		// defaultMessage);

		// (note that @NotBlank is Hibernate-specific API but achieves the same
		// as an annotation on the field)

		LocalDate dateOfBirth = volunteer.getDateOfBirth();
		if (dateOfBirth != null && dateOfBirth.isAfter(LocalDate.now(SessionUtil.getFacilityContext().getTimeZone()))) {
			errors.rejectValue("volunteer.dateOfBirth", "volunteer.error.dateOfBirthNotInFuture");
		}

		String phoneNum = volunteer.getPhone();
		if (!StringUtils.isBlank(phoneNum) && !validatePhoneNumber(phoneNum))
			errors.rejectValue("volunteer.phone", "volunteer.error.phone");

		String phoneAltNum = volunteer.getPhoneAlt();
		if (!StringUtils.isBlank(phoneAltNum) && !validatePhoneNumber(phoneAltNum))
			errors.rejectValue("volunteer.phoneAlt", "volunteer.error.phone");

		String phoneAlt2Num = volunteer.getPhoneAlt2();
		if (!StringUtils.isBlank(phoneAlt2Num) && !validatePhoneNumber(phoneAlt2Num))
			errors.rejectValue("volunteer.phoneAlt2", "volunteer.error.phone");

		String emgergencyPhone = volunteer.getEmergencyContactPhone();
		if (!StringUtils.isBlank(emgergencyPhone) && !validatePhoneNumber(emgergencyPhone))
			errors.rejectValue("volunteer.emergencyContactPhone", "volunteer.error.phone");

		String emgergencyPhoneAlt = volunteer.getEmergencyContactPhoneAlt();
		if (!StringUtils.isBlank(emgergencyPhoneAlt) && !validatePhoneNumber(emgergencyPhoneAlt))
			errors.rejectValue("volunteer.emergencyContactPhoneAlt", "volunteer.error.phone");

		String email = volunteer.getEmail();
		if (!StringUtils.isBlank(email) && !isValidEmailAddress(email))
			errors.rejectValue("volunteer.email", "volunteer.error.email");
	}

	private static boolean validatePhoneNumber(String phoneNo) {
		return phoneNo == null || phoneNo.matches(ValidationUtil.PHONE_REGEX);
	}

	public boolean isValidEmailAddress(String email) {
		return email == null || email.matches(ValidationUtil.EMAIL_REGEX);
	}
}
