package jp.sf.amateras.mirage.example.page;

import static jp.sf.amateras.mirage.test.MirageTestContext.*;
import static org.junit.Assert.*;

import java.util.ArrayList;
import java.util.List;

import jp.sf.amateras.mirage.example.entity.Book;

import org.apache.click.Context;
import org.apache.click.MockContext;
import org.apache.click.servlet.MockRequest;
import org.junit.Test;

public class BookListPageTest extends AbstractPageTest<BookListPage> {

	private static Book newBook(Long id){
		Book book = new Book();
		book.setId(id);
		return  book;
	}

	private static Book newBook(Long id, boolean checked){
		Book book = new Book();
		book.setId(id);
		book.setCheck(checked);
		return  book;
	}

	@Test
	public void testOnInit() {
		List<Book> bookList = new ArrayList<Book>();
		bookList.add(newBook(new Long(1)));
		bookList.add(newBook(new Long(2)));

		addResult(bookList);

		page.onInit();

		@SuppressWarnings("unchecked")
		List<Object> rowList = page.table.getRowList();

		assertEquals(2, rowList.size());
		assertEquals(new Long(1), ((Book) rowList.get(0)).getId());
		assertEquals(new Long(2), ((Book) rowList.get(1)).getId());

		verifySqlNumber(1);
		verifySqlByRegExp(0, "SELECT .* FROM BOOK ORDER BY ID DESC");
	}

	@Test
	public void testOnInit_SubmitClicked() {
		MockContext context = (MockContext) Context.getThreadLocalContext();
		MockRequest request = (MockRequest) context.getRequest();
		request.setParameter("submit", "true");
		request.setParameter("keyword", "keyword");

		page.onInit();

		verifySqlNumber(1);

		verifySqlByRegExp(0, "SELECT .* FROM BOOK " +
				"WHERE NAME LIKE \\? OR AUTHOR LIKE \\? OR PUBLISHER LIKE \\? " +
				"ORDER BY ID DESC",
				"%keyword%", "%keyword%", "%keyword%");
	}

	@Test
	public void testDoDelete() {
		page.delete.setParameter("id", "1");

		page.onInit();
		page.doDelete();

		verifySqlNumber(2);

		verifySqlByRegExp(0, "SELECT .* FROM BOOK ORDER BY ID DESC");
		verifySql(1, "DELETE FROM BOOK WHERE ID=?", new Long(1));
	}

	@Test
	public void testDoBatchDelete() {
		List<Book> bookList = new ArrayList<Book>();
		bookList.add(newBook(new Long(1), true));
		bookList.add(newBook(new Long(2), false));
		bookList.add(newBook(new Long(3), true));

		addResult(bookList);

		page.onInit();
		page.doBatchDelete();

		verifySqlNumber(3);

		verifySqlByRegExp(0, "SELECT .* FROM BOOK ORDER BY ID DESC");
		verifyDeleteSql(1, bookList.get(0));
		verifyDeleteSql(2, bookList.get(2));
	}

}
