/***
 * 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.dom.person;

import java.util.ArrayList;
import java.util.List;

import org.nakedobjects.applib.AbstractDomainObject;
import org.nakedobjects.applib.annotation.Disabled;
import org.nakedobjects.applib.annotation.Hidden;
import org.nakedobjects.applib.annotation.MemberOrder;
import org.nakedobjects.applib.util.TitleBuffer;

public class Person extends AbstractDomainObject {

	// {{ Identification
	public String title() {
		TitleBuffer buf = new TitleBuffer();
		if (getName() != null) {
			buf.append(getName().title());
		}
		buf.append(" (Person)");
		return buf.toString();
	}
	public String iconName() {
		return getName() != null? getName().getTitle().getIconName(): null;
	}
	// }}


	// {{ Lifecycle methods
	public void created() {
		name = newTransientInstance(Name.class);
	}
	// }}

	
	// {{ Name
	private Name name;
	@Disabled
	@MemberOrder(sequence = "1")
	public Name getName() {
		return name;
	}

	public void setName(final Name name) {
		this.name = name;
	}
	// }}


	// {{ Roles
	private List<PersonRole> roles = new ArrayList<PersonRole>();

	@MemberOrder(sequence = "2")
	@Disabled
	public List<PersonRole> getRoles() {
		return roles;
	}

	public void setRoles(final List<PersonRole> roles) {
		this.roles = roles;
	}

	public void addToRoles(final PersonRole role) {
		// check for no-op
		if (role == null
				|| getRoles().contains(role)) {
			return;
		}
		// dissociate arg from its current parent (if any).
		role.clearPerson();
		// associate arg
		role.setPerson(this);
		getRoles().add(role);
		// additional business logic
		onAddToRoles(role);
	}

	public void removeFromRoles(
			final PersonRole role) {
		// check for no-op
		if (role == null
				|| !getRoles().contains(role)) {
			return;
		}
		// dissociate arg
		role.setPerson(null);
		getRoles().remove(role);
		// additional business logic
		onRemoveFromRoles(role);
	}

	protected void onAddToRoles(final PersonRole role) {
	}

	protected void onRemoveFromRoles(final PersonRole role) {
	}
	
	@SuppressWarnings("unchecked")
	@Hidden
	public <T extends PersonRole> T getRole(Class<T> roleType) {
		for(PersonRole role: getRoles()) {
			if (roleType.isAssignableFrom(role.getClass())) {
				return (T) role;
			}
		}
		return null;
	}
	@Hidden
	public boolean hasRole(Class<? extends PersonRole> roleType) {
		return getRole(roleType) != null;
	}
	// }}



	// {{ Helpers
	@Hidden
	public boolean matches(final String firstName, final String lastName) {
		return getName() != null ? getName().matches(firstName, lastName) : false;
	}
	// }}

}
