package jp.co.y_net.amm.api;

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

import jp.co.y_net.amm.dao.Grp;
import jp.co.y_net.amm.dao.GrpDao;
import jp.co.y_net.amm.dao.Grpusr;
import jp.co.y_net.amm.dao.GrpusrDao;
import jp.co.y_net.amm.dao.Usr;
import jp.co.y_net.amm.dao.UsrDao;

import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.spring.injection.annot.SpringBean;

public class ApiGroupmember extends ApiPage {
    
    @SpringBean(name="usrDao")
    protected UsrDao usrDao;
    
    @SpringBean(name="grpDao")
    protected GrpDao grpDao;
    
    @SpringBean(name="grpusrDao")
    protected GrpusrDao grpusrDao;
    
    public ApiGroupmember(PageParameters pageParams) {
        
        String grpid = pageParams.get("grpid").toString();
        List<Result> listResult = new ArrayList<Result>();
        
        
        if(grpid == null) {
            setResponse(new Result().err("パラメータ grpid が指定されていません。"));
            return;
            
        } else {
            try {
                Integer iGrpid = Integer.parseInt(grpid);
                Grp grp = grpDao.getByGrpid(iGrpid);
                
                if(grp == null) {
                    setResponse(new Result().err("指定された grpid からデータが取得できませんでした。"));
                    return;

                } else {
                    
                    Grpusr cndGrpusr = new Grpusr();
                    cndGrpusr.setGrpid(iGrpid);
                    cndGrpusr.setStatus(Grpusr.STATUS_参加中);
                    List<Grpusr> list = grpusrDao.get(cndGrpusr);
                    
                    /* 戻り値作成 */
                    for(Grpusr gu: list) {
                        Usr u = usrDao.getByUsrid(gu.getUsrid());
                        Result r = new Result();
                        //r.usrloginid = URLEncoder.encode(u.getLoginid(), "UTF-8"); // URLエンコード;
                        r.usrloginid = u.getLoginid();
                        r.usrname = u.getName();
                        
                        listResult.add(r);
                    }
                }
            } catch (NumberFormatException e) {
                setResponse(new Result().err("パラメータ grpid は不正です。"));
                return;
            }
        }
        
        /* JSONのレスポンスを設定 */
        setResponse(listResult);
    }
    /**
     * 処理結果
     */
    public static class Result extends ApiResult{
        public String usrloginid;
        public String usrname;
    }
}
