package jp.bne.deno.ordermaid.view;

import java.io.IOException;
import java.util.Date;

import jp.bne.deno.ordermaid.dao.OrderTable;
import jp.bne.deno.ordermaid.model.OrderData;
import jp.bne.deno.ordermaid.model.OrderDetail;
import jp.bne.deno.ordermaid.service.PrinterService;

import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.CompoundPropertyModel;

import com.google.inject.Inject;

/**
 * @author hasegawt. メニュー画面
 */
public class OrderPage extends BasePage {

	@Inject
	OrderTable orderTable;

	@Inject
	PrinterService printerService;

	private OrderData order;

	Form<OrderData> form;

	public OrderPage() {
		this(new OrderData());
	}

	public OrderPage(OrderData orderData) {
		order = orderData;

		order.setOrderDate(new Date());
		form = new Form<OrderData>("form",
				new CompoundPropertyModel<OrderData>(order));

		form.add(new FeedbackPanel("feedback"));
		form.add(new Label("version"));
		form.add(new Label("orderDate"));
		form.add(new Button("add") {
			// 明細追加ボタン
			@Override
			public void onSubmit() {
				OrderDetail detail = new OrderDetail();
				order.getDetails().add(detail);
				detail.setOrder(order);
				setResponsePage(new OrderDetailPage(detail));
			}
		});
		form.add(new Button("commit") {
			// 登録ボタン
			@Override
			public void onSubmit() {
				order.setOrderDate(new Date());
				orderTable.addOrder(order);
				try {
					printerService.printOrder(order);
					setResponsePage(new IndexPage());
				} catch (IOException e) {
					error(e.getMessage());
				}
			}
		});

		form.add(new ListView<OrderDetail>("details") {
			@Override
			protected void populateItem(ListItem<OrderDetail> item) {
				final OrderDetail detail = item.getModelObject();
				item.setModel(new CompoundPropertyModel<OrderDetail>(detail));
				item.add(new Label("sheetId"));
				item.add(new Label("sumPrice"));
				item.add(new Label("menus"));

				item.add(new Button("update") {
					// 明細更新ボタン
					@Override
					public void onSubmit() {
						setResponsePage(new OrderDetailPage(detail));
					}
				});
				item.add(new Button("delete") {
					// 明細削除ボタン
					@Override
					public void onSubmit() {
						orderTable.removeOrderDetail(detail);
						order.getDetails().remove(detail);
					}
				});
				item.add(new Button("copy") {
					// 明細複製ボタン
					@Override
					public void onSubmit() {
						OrderDetail dest = new OrderDetail(detail);
						order.getDetails().add(dest);
						setResponsePage(new OrderDetailPage(dest));
					}
				});

			}
		});
		add(form);
	}

	public void setOrderData(OrderData order) {
		this.order = order;
		form.setModel(new CompoundPropertyModel<OrderData>(order));
	}
}
