package jp.bne.deno.ordermaid.view.admin;

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

import jp.bne.deno.ordermaid.dao.SystemTable;
import jp.bne.deno.ordermaid.model.SystemItem;
import jp.bne.deno.ordermaid.view.BasePage;

import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextField;
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 SystemItemPage extends BasePage {

	List<SystemItem> items = new ArrayList<SystemItem>();

	private String newKey;
	private String newValue;
	private String newNote;

	@Inject
	SystemTable table;

	public SystemItemPage() {

		Form<SystemItemPage> form = new Form<SystemItemPage>("form",
				new CompoundPropertyModel<SystemItemPage>(this));
		form.add(new FeedbackPanel("feedback"));

		form.add(new TextField<String>("newKey"));
		form.add(new TextField<String>("newValue"));
		form.add(new TextField<String>("newNote"));
		items = table.findAll();

		form.add(new Button("add") {
			public void onSubmit() {
				SystemItem item = new SystemItem();
				item.setKey(newKey);
				item.setValue(newValue);
				item.setNote(newNote);
				try {
					table.save(item);
					newKey = "";
					newValue = "";
					newNote = "";
					items = table.findAll();
				} catch (Throwable e) {
					error(e.getMessage());
				}

			}
		});
		form.add(new ListView<SystemItem>("items") {
			protected void populateItem(ListItem<SystemItem> item) {
				final SystemItem systemItem = item.getModelObject();
				item
						.setModel(new CompoundPropertyModel<SystemItem>(
								systemItem));
				item.add(new TextField<String>("key"));
				item.add(new TextField<String>("value"));
				item.add(new TextField<String>("note"));
				item.add(new Button("save") {
					public void onSubmit() {
						try {
							table.save(systemItem);
							items = table.findAll();
						} catch (Throwable e) {
							error(e.getMessage());
						}
					}
				});
			}
		});
		add(form);
	}

}
