package org.hibernate.auction.test;

import junit.framework.*;
import junit.textui.TestRunner;
import org.hibernate.auction.dao.*;
import org.hibernate.auction.exceptions.*;
import org.hibernate.auction.model.*;
import org.hibernate.auction.persistence.HibernateUtil;

import java.math.BigDecimal;
import java.util.*;

public class ItemTest extends TestCaseWithData {

	// ********************************************************** //

	public void testItemData() throws Exception {
		initData();

		ItemDAO itemDAO = new ItemDAO();

		Item a1 = itemDAO.getItemById(auctionOne.getId(), false);
		assertEquals(a1.getInitialPrice(),
		             new MonetaryAmount(new BigDecimal("1.99"), Currency.getInstance(Locale.US)));

		HibernateUtil.commitTransaction();
		HibernateUtil.closeSession();
	}

	// ********************************************************** //

	public void testPlaceBid() throws Exception {
		initData();

		// TODO: Test niepoprawnie uwzględnia waluty!

		ItemDAO itemDAO = new ItemDAO();
		UserDAO userDAO = new UserDAO();

		Bid currentMaxBid = itemDAO.getMaxBid(auctionTwo.getId());
		Bid currentMinBid = itemDAO.getMinBid(auctionTwo.getId());
		Item a2 = itemDAO.getItemById(auctionTwo.getId(), true);

		// Błąd, aukcja jeszcze nie jest aktywna.
		try {
			BigDecimal bidAmount = new BigDecimal("99.99");
			MonetaryAmount newAmount = new MonetaryAmount(bidAmount, Currency.getInstance("USD"));
			a2.placeBid(userDAO.getUserById(u3.getId(), false),
									newAmount,
									currentMaxBid,
									currentMinBid);
		} catch (BusinessException success) {}

		// Błąd, użytkownik nie jest administratorem.
		try {
			a2.approve(u3);
		} catch (PermissionException success) {}

		// Poprawne, uaktywnienie.
		a2.setPendingForApproval();
		a2.approve(u1);

		// Udane, umieszczenie oferty.
		try {
			BigDecimal bidAmount = new BigDecimal("100.00");
			MonetaryAmount newAmount = new MonetaryAmount(bidAmount, Currency.getInstance("USD"));
			a2.placeBid(userDAO.getUserById(u3.getId(), false),
									newAmount,
									currentMaxBid,
									currentMinBid);

		} catch (BusinessException failure) {
			throw failure;
		}

		// Błąd, oferta za niska.
		try {
			BigDecimal bidAmount = new BigDecimal("99.99");
			MonetaryAmount newAmount = new MonetaryAmount(bidAmount, Currency.getInstance("USD"));
			a2.placeBid(userDAO.getUserById(u3.getId(), false),
									newAmount,
									currentMaxBid,
									currentMinBid);
		} catch (BusinessException success) {}

		// TODO: Implementacja testów dla dat aukcji...

		HibernateUtil.commitTransaction();
		HibernateUtil.closeSession();

	}

	// ********************************************************** //

	public ItemTest(String x) {
		super(x);
	}

	public static Test suite() {
		return new TestSuite(ItemTest.class);
	}

	public static void main(String[] args) throws Exception {
		TestRunner.run( suite() );
	}

}
