package gov.va.vss.web.donation;

import java.time.LocalDate;
import java.time.ZoneId;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;

import gov.va.vss.model.donation.DonationSummary;
import gov.va.vss.util.DateUtil;
import gov.va.vss.util.context.SessionUtil;
import gov.va.vss.web.AbstractAppValidator;

@Component
public class DonationValidator extends AbstractAppValidator<DonationCommand> {

	@Autowired
	private DateUtil dateUtil;

	@Override
	public void doExtraValidations(DonationCommand command, Errors errors) {
		DonationSummary donationSummary = command.getDonationSummary();

		// for example: CPB

		// No need to check null for donation date since it has been set to
		// default if it is null in database
		ZoneId myTimeZone = SessionUtil.getFacilityContext().getTimeZone();
		if (!command.isProcessingEDonation()) {
			// if in the process of adding eDonation then by pass this rule
			LocalDate donationDate = command.getDonationSummary().getDonationDate();
			if (donationDate.isBefore(dateUtil.getEarliestAcceptableDateEntryAsOfNow(myTimeZone))
					|| donationDate.isAfter(command.getCurrentFiscalYearEndDate())) {
				errors.rejectValue("donationSummary.donationDate",
						"donationSummary.error.donationDateNotWhthinFiscalYear");

			}
		}

		if (donationSummary.getDonationDate().isAfter(LocalDate.now(myTimeZone)))
			errors.rejectValue("donationSummary.donationDate", "donationSummary.error.donationDate");

		if (donationSummary.getAcknowledgementDate() != null
				&& donationSummary.getDonationDate().isAfter(donationSummary.getAcknowledgementDate()))
			errors.rejectValue("donationSummary.acknowledgementDate", "donationSummary.error.acknowledgementDate");

		if (donationSummary.getDonReference() != null && donationSummary.getDonReference().isInactive()
				&& (command.getPreviousDonRef() == null || !donationSummary.getDonReference().getDonationReference()
						.equalsIgnoreCase(command.getPreviousDonRef().getDonationReference())))
			errors.rejectValue("donationSummary.donReference", "donationSummary.error.donReference");
	}

}
