package jp.co.y_net.amm.api;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
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 ApiMembergroup extends ApiPage {
    
    @SpringBean(name="usrDao")
    protected UsrDao usrDao;
    
    @SpringBean(name="grpDao")
    protected GrpDao grpDao;
    
    @SpringBean(name="grpusrDao")
    protected GrpusrDao grpusrDao;
    
    public ApiMembergroup(PageParameters pageParams) {
        
        String loginid = pageParams.get("loginid").toString();
        List<Result> listResult = new ArrayList<Result>();
        
        if(loginid == null) {
            setResponse(new Result().err("パラメータ loginid が指定されていません。"));
            return;
        } else {
            try {
                loginid = URLDecoder.decode(loginid, "UTF-8"); // URLデコード
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
            Usr usr = usrDao.getByLoginid(loginid);
            
            if(usr == null) {
                setResponse(new Result().err("指定された loginid からデータが取得できませんでした。"));
                return;
            } else {
                
                Grpusr cndGrpusr = new Grpusr();
                cndGrpusr.setUsrid(usr.getUsrid());
                cndGrpusr.setStatus(Grpusr.STATUS_参加中);
                List<Grpusr> list = grpusrDao.get(cndGrpusr);
                
                /* 戻り値作成 */
                for(Grpusr gu: list) {
                    Integer grpid = gu.getGrpid();
                    Grp g = grpDao.getByGrpid(gu.getGrpid());
                    Result r = new Result();
                    r.grpid = grpid;
                    r.grpname = g.getName();
                    
                    listResult.add(r);
                }
            }
        }
        
        /* JSONのレスポンスを設定 */
        setResponse(listResult);
    }
    /**
     * 処理結果
     */
    public static class Result extends ApiResult{
        public Integer grpid;
        public String grpname;
    }
}
