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

import java.util.List;

import org.nakedobjects.applib.AbstractFactoryAndRepository;
import org.nakedobjects.applib.Filter;
import org.nakedobjects.applib.annotation.Hidden;
import org.nakedobjects.applib.annotation.MemberOrder;

import com.domainlanguage.time.CalendarDate;
import com.pragprog.dhnako.carserv.dom.domainservices.CalendarService;
import com.pragprog.dhnako.carserv.dom.service.Service;
import com.pragprog.dhnako.carserv.dom.vehicle.Car;
import com.pragprog.dhnako.carserv.dom.vehicle.CarRepository;
import com.pragprog.dhnako.carserv.dom.vehicle.Model;
import com.pragprog.dhnako.carserv.dom.vehicle.RegistrationNumber;

public class CarRepositoryInMemory extends AbstractFactoryAndRepository implements CarRepository {


	// {{ Identification
	public String iconName() {
		return "Car";
	}
	// }}


	// {{ FindByRegistrationNumber
	@MemberOrder(sequence = "1")
	public Car findByRegistrationNumber(
	        final RegistrationNumber registrationNumber) {
	    return firstMatch(Car.class, new Filter<Car>() {
	        public boolean accept(final Car car) {
	            return car.getRegistrationNumber().equals(registrationNumber);
	        }});
	}
	// }}
	
	
	// {{ findCarsWithoutRecentService
	@Hidden
    public List<Car> findCarsWithoutRecentService(
    	final Model model, 
    	final Integer months) {
        final CalendarDate earlierDate = 
            calendarService.today().plusMonths(-months);
        return allMatches(Car.class, new Filter<Car>() {
            public boolean accept(Car car) {
                if (car.getModel() != model) return false;
                Service service = car.mostRecentService();
                return service != null && 
                       service.getBookedInAndReady()
                              .start().isBefore(earlierDate);
            }});
    }
	
	
	// {{ all Cars
	@MemberOrder(sequence = "2")
	public List<Car> allCars() {
		return allInstances(Car.class);
	}
    // }}

    
    
	// {{ injected: CalendarService
	private CalendarService calendarService;

	public void setCalendarService(final CalendarService calendarService) {
		this.calendarService = calendarService;
	}
	// }}


}
