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

import jp.sf.amateras.mirage.SqlManager;
import jp.sf.amateras.mirage.example.entity.Book;
import jp.sf.amateras.mirage.example.page.BookListPage.BookSearchParam;

import org.apache.click.ActionListener;
import org.apache.click.Control;
import org.apache.click.control.FileField;
import org.apache.click.control.Form;
import org.apache.click.control.PageLink;
import org.apache.click.control.Submit;
import org.apache.click.control.TextField;
import org.apache.click.extras.control.DateField;
import org.apache.click.extras.control.IntegerField;

public class BookRegisterPage extends AbstractPage {

	private static final long serialVersionUID = 1L;

	private Form form = new Form("form");

	private TextField name = new TextField("name", getMessage("book.name"), 40, true);
	private TextField author = new TextField("author", getMessage("book.author"), 40, true);
	private TextField publisher = new TextField("publisher", getMessage("book.publisher"), 40, true);
	private IntegerField price = new IntegerField("price", getMessage("book.price"), 10, true);
	private DateField publishDate = new DateField("publishDate", getMessage("book.publishDate"), true);
	private FileField image = new FileField("image", getMessage("book.image"));
	private Submit submit = new Submit("submit", getMessage("button.register"));

	private PageLink back = new PageLink("back", getMessage("link.back"), BookListPage.class);

	@Override
	public void onInit() {
		super.onInit();

		// Removes search condition from session
		getContext().removeSessionAttribute(BookSearchParam.class.getName());

		// Assembles form
		form.add(name);
		form.add(author);
		form.add(publisher);
		form.add(price);
		form.add(publishDate);
		form.add(image);
		form.add(submit);

		submit.setActionListener(new ActionListener() {
			private static final long serialVersionUID = 1L;
			@Override
			public boolean onAction(Control source) {
				if(form.isValid()){
					Book book = new Book();
					form.copyTo(book);
					book.setImageName(image.getFileItem().getName());
					book.setImage(image.getFileItem().get());

					SqlManager sqlManager = getSqlManager();
					sqlManager.insertEntity(book);
					setRedirect(BookListPage.class);
					return false;
				}
				return true;
			}
		});

		addControl(form);
		addControl(back);
		addModel("title", getMessage("title.bookRegister"));
	}

}
