package jp.co.y_net.amm.page;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map.Entry;

import jp.co.y_net.amm.AppSession;
import jp.co.y_net.amm.common.ChoiceElement;
import jp.co.y_net.amm.common.ResourceReader;
import jp.co.y_net.amm.dao.Org;
import jp.co.y_net.amm.dao.Usr;

import org.apache.commons.lang.StringUtils;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.DropDownChoice;
import org.apache.wicket.markup.html.link.ExternalLink;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.PageableListView;
import org.apache.wicket.markup.html.navigation.paging.PagingNavigator;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.LoadableDetachableModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.request.mapper.parameter.PageParameters;

public class OrgEntryListPage extends CommonFrameA {
	private static final long serialVersionUID = 1L;

    /**
     * ログインチェック定義
     * @see jp.co.y_net.amm.page.AppPage#validateLogin()
     */
    @Override
    public boolean validateLogin() {
        if(AppSession.get().isLogin()) {
            if(AppSession.get().getLoginUser().getKind().equals(Usr.KIND_運営管理者)) {
                return true;
            }
        }
        return false;
    }
    
    public OrgEntryListPage(PageParameters pageParams) {
        
        /* 戻るリンク */
        add(new ExternalLink("lnkSysAdmin", ResourceReader.getStringQuick("url.back.sysadmin")));
        
        /* フィードバックメッセージ */
        add(new FeedbackPanel("feedback"));
        

        /* 表示順序 */
        List<ChoiceElement> sortChoice = new ArrayList<ChoiceElement>();
        sortChoice.add(new ChoiceElement("1","申請日時の新しい順"));
        sortChoice.add(new ChoiceElement("2","申請日時の古い順"));
        final Model<ChoiceElement> sortModel = new Model<ChoiceElement>();
        ChoiceElement.setDropDownList(sortModel, sortChoice, "1"); // 初期値設定
        final DropDownChoice<ChoiceElement> sortEntrydate = new DropDownChoice<ChoiceElement>(
                "sortEntrydate", sortModel, sortChoice, new ChoiceElement.Renderer());
        add(sortEntrydate);
        
        /* 絞り込み */
        List<ChoiceElement> filterChoice = new ArrayList<ChoiceElement>();
        filterChoice.add(new ChoiceElement(" ","全て"));
        for(Entry<String, String> entry: Org.getStatusMap().entrySet()) {
            filterChoice.add(new ChoiceElement(entry.getKey(), entry.getValue()));
        }
        final Model<ChoiceElement> filterModel = new Model<ChoiceElement>();
        ChoiceElement.setDropDownList(filterModel, filterChoice, " "); // 初期値設定
        final DropDownChoice<ChoiceElement> filterStatus = new DropDownChoice<ChoiceElement>(
                "filterStatus", filterModel, filterChoice, new ChoiceElement.Renderer());
        add(filterStatus);
        
        // LoadableDetachableModel は リクエストの最初に load にてデータを取得するモデル
        final IModel<List<Org>> orgsModel = new LoadableDetachableModel<List<Org>>() {
            @Override
            protected List<Org> load() {
                Org cnd = new Org();
                if(filterModel.getObject() != null) {
                    String filterId = filterModel.getObject().getId();
                    if(filterId != null && filterId.trim().equals("") == false) {
                        int iFilterId = Integer.parseInt(filterId);
                        cnd.setStatus(iFilterId);
                    }
                }
                List<Org> entryOrgs = orgDao.get(cnd);
                
                boolean desc = sortModel.getObject().getId().equals("1");
                Collections.sort(entryOrgs, new Org.EntryDateComparator(desc));
                
                return entryOrgs;
            }
        };
        
        final WebMarkupContainer container = new WebMarkupContainer("listViewContainer");
        container.setOutputMarkupId(true);
        add(container);
        final PageableListView<Org> listview = new PageableListView<Org>("listview", orgsModel, 20) {
            private static final long serialVersionUID = 1L;
            @Override
            protected void populateItem(ListItem<Org> item) {
//                
                final Org org = item.getModelObject();
                
                /* 会員種別 */
                item.add(new Label("kind", org.getKind_Disp()));
                
                
                /* 名称とリンク */
                //BookmarkablePageLink<Void> lnkName = new BookmarkablePageLink<Void>("lnkName", OrgEntryDetailPage.class, param);
                Link<Void> lnkName = new Link<Void>("lnkName"){
                    @Override
                    public void onClick() {
                        PageParameters param = new PageParameters();
                        param.add("orgid", org.getOrgid());
                        OrgEntryDetailPage nextPage = new OrgEntryDetailPage(param);
                        nextPage.setReturnPage(getPage()); // このページを戻り先として記録する
                        setResponsePage(nextPage);
                    }
                };
                
                
                String name = org.getNameOrAdminname();
                if(StringUtils.isEmpty(name)) {
                    name = "※"; // 仮に値が取得できない場合でも、リンクに使用されるため、疑似値を設定した。
                }
                Label lnklblName = new Label("lnklblName", name);
                lnkName.add(lnklblName);
                item.add(lnkName);
                
                /* ステータス */
                item.add(new Label("status", org.getStatus_Disp()));
                
                /* 申請日時 */
                item.add(new Label("entrydate" , org.getEntrydate_Disp()));
            }
        };
        container.add(listview);
        
        PagingNavigator navigator = new PagingNavigator("paging", listview){
            @Override
            public boolean isVisible() {
                return listview.size() > 0;
            }
        };
        add(navigator);
        
        
        /* プルダウン変更の挙動 */
        sortEntrydate.add(new AjaxFormComponentUpdatingBehavior("onchange") {
            @Override
            protected void onUpdate(AjaxRequestTarget target) {
                target.add(container);
            }
        });
        filterStatus.add(new AjaxFormComponentUpdatingBehavior("onchange") {
            @Override
            protected void onUpdate(AjaxRequestTarget target) {
                target.add(container);
            }
        });
    }
}
