package jp.arcanum.myaddress.pages.list;

import java.util.List;
import java.util.Map;

import org.apache.wicket.PageParameters;
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.link.Link;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.markup.html.list.PageableListView;
import org.apache.wicket.model.Model;

import jp.arcanum.myaddress.pages.AbstractPage;
import jp.arcanum.myaddress.pages.update.AddPage;
import jp.arcanum.myaddress.pages.update.DeletePage;
import jp.arcanum.myaddress.pages.update.UpdatePage;
import jp.arcanum.myaddress.util.MyUtil;

public class ListPage extends AbstractPage{

	
	/**
	 * コンストラクタ
	 *
	 */
	public ListPage(){
		
		//　追加ボタン
		Button add = new Button("ADD"){
			public void onSubmit(){
				onClickAdd();
			}
		};
		_form.add(add);
		
		//　一覧
		List list = selectAddressList();
		ListView listview = new ListView("LIST", list){
			public void populateItem(ListItem item){
				
				Map record = (Map)item.getModelObject();
				final Integer addrid = (Integer)record.get("ADDRID");
				
				//　名前
				String name = (String)record.get("NAME_KANJI");
				Label lblname = new Label("NAME_KANJI",new Model(name));
				item.add(lblname);
				
				//　住所
				String addr = (String)record.get("ADDRESS");
				if(addr.length()>50){
					addr = addr.substring(0,50);
				}
				Label lbladdr = new Label("ADDRESS", new Model(addr));
				item.add(lbladdr);
				
				//　更新/削除
				Link linkupd = new Link("UPDATE"){
					public void onClick(){
						onClickUpdate(addrid.intValue());
					}
				};
				Link linkdel = new Link("DELETE"){
					public void onClick(){
						onClickDelete(addrid.intValue());
					}
				};
				item.add(linkupd);
				item.add(linkdel);
				
			}
		};
		_form.add(listview);
		
		
	}
	
	/**
	 * 追加ボタン処理
	 *
	 */
	public void onClickAdd(){
		
		setResponsePage(AddPage.class);
		
	}
	
	/**
	 * 更新リンク処理
	 * @param addrid
	 */
	public void onClickUpdate(int addrid){
	
		
		PageParameters param = new PageParameters();
		param.put(ADDRID, Integer.toString(addrid));
		
		setResponsePage(UpdatePage.class, param);

	}
	
	/**
	 * 削除リンク処理
	 * @param addrid
	 */
	public void onClickDelete(int addrid){
		
		PageParameters param = new PageParameters();
		param.put(ADDRID, new Integer(addrid));
		
		setResponsePage(DeletePage.class, param);
		
	}
	
	
	/**
	 * アドレス帳から全件取得します
	 * @return 
	 */
	private List selectAddressList(){
		
		List ret = null;
		
		//　ＳＱＬを編集
		String sql = "SELECT * FROM MYADDRESS ";
		
		ret = MyUtil.select(sql);
		
		return ret;
		
	}
	
	
}
