package org.sistema.spring.ws.carinsurance;

import javax.annotation.PostConstruct;
import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.datatype.DatatypeFactory;

import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

@Component
public class CarDatasource {
	private static final List<Car> cars = new ArrayList<Car>();

	@PostConstruct
	public void initData() {
		Insurance insurance1 = new Insurance();
		insurance1.setCompany("Mapfre");
		insurance1.setDate(generateDate());
		
		Car car1 = new Car();
		car1.setPlate("0042ASM");
		car1.setYear(2012);
		car1.setBrand("Tesla");
		car1.setInsurance(insurance1);	

		cars.add(car1);

		Insurance insurance2 = new Insurance();
		insurance2.setCompany("AIG");
		insurance2.setDate(generateDate());
		
		Car car2 = new Car();
		car2.setPlate("0666EVL");
		car2.setYear(2003);
		car2.setBrand("Opel Corsa");
		car2.setInsurance(insurance2);	

		cars.add(car2);
		
		Insurance insurance3 = new Insurance();
		insurance3.setCompany("Lloyds");
		insurance3.setDate(generateDate());
		
		Car car3 = new Car();
		car3.setPlate("2501LBV");
		car3.setYear(2012);
		car3.setBrand("Seat");
		car3.setInsurance(insurance3);	

		cars.add(car3);
		
	}

	/**
	 * finds a car through its plate number
	 * @param plate
	 * @return
	 */
	public Car findCar(String plate) {
		Assert.notNull(plate);

		Car found = null;

		for (Car car : cars) {
			if (plate.equals(car.getPlate())) {
				found = car;
			}
		}

		return found;
	}
	

	/**
	 * generates a date in XMLGregorianCalendar format
	 * @return
	 */
	private XMLGregorianCalendar generateDate () {
		XMLGregorianCalendar date = null;
		GregorianCalendar c = new GregorianCalendar();
		c.setTime(new Date());
		try {
			date = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);
		} catch (Exception e) {
			System.err.println("Error generating date");
		}
		return date;
		
	}

}
