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

import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;

import org.nakedobjects.applib.AbstractDomainObject;
import org.nakedobjects.applib.ApplicationException;
import org.nakedobjects.applib.annotation.Bounded;
import org.nakedobjects.applib.annotation.Hidden;
import org.nakedobjects.applib.annotation.Immutable;
import org.nakedobjects.applib.annotation.MemberOrder;
import org.nakedobjects.applib.annotation.Optional;
import org.nakedobjects.applib.annotation.When;

@NamedQueries({
	@NamedQuery(
			name="findVehicleTypeByFullyQualifiedClassName", 
			query="from VehicleType where fullyQualifiedClassName=:fullyQualifiedClassName")
})
@Entity
@Bounded
@Immutable(When.ONCE_PERSISTED)
@DiscriminatorValue("VTP")
public class VehicleType extends AbstractDomainObject {

	// {{ Identification
    public String title() {
        return vehicleSubclass().getSimpleName();
    }
    public String iconName() {
		return title();
	}
    // }}

    
    // {{ Id
    private Long id;
    @Hidden
	@Optional
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
    // }}
    
    
    // {{ FullyQualifiedClassName
	private String fullyQualifiedClassName;

	@MemberOrder(sequence = "1")
	public String getFullyQualifiedClassName() {
		return fullyQualifiedClassName;
	}

	public void setFullyQualifiedClassName(final String fullyQualifiedClassName) {
		this.fullyQualifiedClassName = fullyQualifiedClassName;
	}
	// }}


	// {{ create
	@Hidden
    public Vehicle create(final Model model) {
        try {
            Vehicle vehicle = newTransientInstance(vehicleSubclass());
            vehicle.setModel(model);
            return vehicle;
        } catch (Exception ex) {
            throw new ApplicationException(ex);
        }
    }
    // }}

	
	// {{ Helpers
    @SuppressWarnings("unchecked")
	private Class<? extends Vehicle> vehicleSubclass() {
        try {
            return (Class<? extends Vehicle>) 
                Class.forName(getFullyQualifiedClassName());
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("No such vehicle type");
        }
    }
    // }}
}