/*
 * This code is sample code, provided as-is, and we make NO 
 * warranties as to its correctness or suitability for any purpose.
 * 
 * We hope that it's useful to you. Enjoy. 
 * Copyright LearningPatterns Inc.
 */

package com.javatunes.domain;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;

import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.javatunes.config.SpringConfig;
import com.javatunes.service.Catalog;

public class UT_Catalog {

	// One TX, everything works properly
	@Test
	public void scenario1() {
		AnnotationConfigApplicationContext spring = new AnnotationConfigApplicationContext(SpringConfig.class);

		Catalog cat = spring.getBean(Catalog.class);

		System.out.println(cat.findById(1L));

		spring.close();
	}

	// Exception thrown, TX rolled back
	@Test
	public void scenario2() {
		AnnotationConfigApplicationContext spring = new AnnotationConfigApplicationContext(SpringConfig.class);

		Catalog cat = spring.getBean(Catalog.class);

		cat.persist(null);

		spring.close();
	}

	// Non-transactional method called - no TX
	@Test
	public void scenario3() {
		AnnotationConfigApplicationContext spring = new AnnotationConfigApplicationContext(SpringConfig.class);

		Catalog cat = spring.getBean(Catalog.class);

		cat.size();

		spring.close();
	}

	// Batch persistence done with one null item that blows up when persisted
	@Test
	public void scenario4() {
		AnnotationConfigApplicationContext spring = new AnnotationConfigApplicationContext(SpringConfig.class);

		Catalog cat = spring.getBean(Catalog.class);

		cat.persistBatch(grabBatch());

		spring.close();
	}


	private Collection<MusicItem> grabBatch() {
		Collection<MusicItem> batch = new ArrayList<MusicItem>();
		add(batch, "New One", "New", "2013-01-04", "13.99", MusicCategory.Rap);
		add(batch, "Another New One", "Newer", "2013-02-05", "14.99", MusicCategory.Pop);
		batch.add(null);
		return batch;
	}

	private void add(Collection<MusicItem> batch, String title, String artist, String releaseDate,String price, MusicCategory musicCategory) {
		batch.add(new MusicItem(title, artist, releaseDate,new BigDecimal(price), musicCategory));
	}
}
