/***
 * Excerpted from "Domain-Driven Design Using Naked Objects",
 * published by The Pragmatic Bookshelf.
 * Copyrights apply to this code. It may not be used to create training material, 
 * courses, books, articles, and the like. Contact us if you are in doubt.
 * We make no guarantees that this code is fit for any purpose. 
 * Visit http://www.pragmaticprogrammer.com/titles/dhnako for more book information.
***/
package com.pragprog.dhnako.carserv.wicket.ui;

import org.apache.wicket.markup.html.form.FormComponent;
import org.apache.wicket.validation.validator.StringValidator;
import org.nakedobjects.metamodel.facets.propparam.validate.maxlength.MaxLengthFacet;
import org.nakedobjects.metamodel.spec.feature.NakedObjectAssociation;
import org.nakedobjects.metamodel.spec.feature.OneToOneAssociation;
import org.nakedobjects.plugins.headless.applib.HeadlessViewer;

import com.pragprog.dhnako.carserv.dom.customer.Customer;

final class EditCustomerFormUsingViewObjectsExtended extends EditCustomerFormUsingViewObjects {
	private static final long serialVersionUID = 1L;

	EditCustomerFormUsingViewObjectsExtended(
			final String id, final HeadlessViewer headlessViewer, final Customer customer) {
		super(id, headlessViewer, customer);
	}

	@Override
	protected void configureNotesFieldRules(final LabelAndFormComponent lafc) {
		super.configureNotesFieldRules(lafc);
		installMaxLengthValidator(Customer.class, lafc.getFormComponent());
	}

	private void installMaxLengthValidator(final Class<?> domainClass, final FormComponent field) {
		NakedObjectAssociation association = getAssociation(domainClass, field);
		MaxLengthFacet maxLengthFacet = association.getFacet(MaxLengthFacet.class);
		if (maxLengthFacet != null) {
			field.add(StringValidator.maximumLength(maxLengthFacet.value()));
		}
	}

	private NakedObjectAssociation getAssociation(final Class<?> domainClass, final FormComponent formComponent) {
		return (OneToOneAssociation) getMetaModel().getSpecificationLoader().loadSpecification(domainClass).getAssociation(formComponent.getId());
	}


}