/*
 * Copyright(C) 2010 avanza Co.,Ltd. All rights reserved.
 * http://www.avnz.co.jp/
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

package com.aimluck.eip.enquete;

import java.util.ArrayList;
import java.util.List;
import java.util.jar.Attributes;

import org.apache.cayenne.exp.Expression;
import org.apache.cayenne.exp.ExpressionFactory;
import org.apache.jetspeed.services.logging.JetspeedLogFactoryService;
import org.apache.jetspeed.services.logging.JetspeedLogger;
import org.apache.turbine.util.RunData;
import org.apache.velocity.context.Context;

import com.aimluck.commons.field.ALStringField;
import com.aimluck.eip.cayenne.om.portlet.AvzTEnquete;
import com.aimluck.eip.cayenne.om.portlet.AvzTEnqueteChoiceItem;
import com.aimluck.eip.cayenne.om.portlet.AvzTEnqueteItem;
import com.aimluck.eip.common.ALAbstractSelectData;
import com.aimluck.eip.common.ALDBErrorException;
import com.aimluck.eip.common.ALData;
import com.aimluck.eip.common.ALEipConstants;
import com.aimluck.eip.common.ALPageNotFoundException;
import com.aimluck.eip.enquete.util.EnqueteUtils;
import com.aimluck.eip.modules.actions.common.ALAction;
import com.aimluck.eip.orm.Database;
import com.aimluck.eip.orm.query.ResultList;
import com.aimluck.eip.orm.query.SelectQuery;
import com.aimluck.eip.util.ALEipUtils;

/**
 * Enquete検索データを管理するクラスです。 <BR>
 * 
 */
public class EnqueteSummaryListSelectData extends
    ALAbstractSelectData<AvzTEnquete, AvzTEnquete> implements ALData {

  /** logger */
  private static final JetspeedLogger logger =
    JetspeedLogFactoryService.getLogger(EnqueteSelectData.class.getName());

  /** ログインユーザーID */
  private int loginuserid;

  /** アンケート項目・選択肢取得リスト */
  private List itemresults;

  /** 回答対象者数 */
  private int answer_sum;

  /** 回答済み人数 */
  private int selected_answer_sum;

  /**
   * 
   * @param action
   * @param rundata
   * @param context
   * @see com.aimluck.eip.common.ALAbstractSelectData#init(com.aimluck.eip.modules.actions.common.ALAction,
   *      org.apache.turbine.util.RunData, org.apache.velocity.context.Context)
   */
  @Override
  public void init(ALAction action, RunData rundata, Context context)
      throws ALPageNotFoundException, ALDBErrorException {

    super.init(action, rundata, context);

  }

  /**
   * 一覧データを取得します。 <BR>
   * 
   * @param rundata
   * @param context
   * @return
   * @see com.aimluck.eip.common.ALAbstractListData#selectData(org.apache.turbine.util.RunData,
   *      org.apache.velocity.context.Context)
   */
  @Override
  public ResultList<AvzTEnquete> selectList(RunData rundata, Context context) {
    return null;
  }

  /**
   * ResultData に値を格納して返します。（一覧データ） <BR>
   * 
   * @param obj
   * @return
   * @see com.aimluck.eip.common.ALAbstractSelectData#getListData(java.lang.Object)
   */
  @Override
  protected Object getResultData(AvzTEnquete obj) {
    return null;
  }

  /**
   * 詳細データを取得します。 <BR>
   * 
   * @param rundata
   * @param context
   * @return
   * @see com.aimluck.eip.common.ALAbstractSelectData#selectDetail(org.apache.turbine.util.RunData,
   *      org.apache.velocity.context.Context)
   */
  @Override
  public AvzTEnquete selectDetail(RunData rundata, Context context)
      throws ALPageNotFoundException {

    try {
      AvzTEnquete enquete = EnqueteUtils.getAvzTEnquete(rundata, context);

      SelectQuery<AvzTEnqueteItem> query =
        Database.query(AvzTEnqueteItem.class);
      Expression exp =
        ExpressionFactory.matchDbExp(AvzTEnqueteItem.AVZ_TENQUETE_PROPERTY
          + "."
          + AvzTEnquete.ENQUETE_ID_PK_COLUMN, ALEipUtils.getTemp(
          rundata,
          context,
          ALEipConstants.ENTITY_ID));
      query.setQualifier(exp);
      query.distinct(true);
      query.orderAscending(AvzTEnqueteItem.ITEM_NUMBER_PROPERTY);

      ResultList<AvzTEnqueteItem> list = query.getResultList();
      itemresults = new ArrayList();
      loginuserid = Integer.valueOf(ALEipUtils.getUserId(rundata));

      // 回答者の一人を取得
      SelectQuery<AvzTEnqueteChoiceItem> answerquery =
        Database.query(AvzTEnqueteChoiceItem.class);

      Expression answerexp =
        ExpressionFactory.matchDbExp(
          AvzTEnqueteChoiceItem.AVZ_TENQUETE_ITEM_PROPERTY
            + "."
            + AvzTEnquete.ENQUETE_ID_PK_COLUMN,
          enquete.getEnqueteId());

      answerquery.setQualifier(answerexp);
      ResultList<AvzTEnqueteChoiceItem> getAnswer = answerquery.getResultList();

      AvzTEnqueteChoiceItem cho = getAnswer.get(0);
      int someAnswer = cho.getAnswerId();

      for (int i = 0; i < list.size(); i++) {

        AvzTEnqueteItem item = list.get(i);
        EnqueteItemRecordData d = new EnqueteItemRecordData();
        ALStringField record = new ALStringField();

        item.getChoiceItemNum();
        int item_id = item.getItemId();
        record.setValue(item.getItemTitle());
        d.setItemId(item_id);
        d.setItemName(record);
        d.setStatus(item.getStatus());
        if (EnqueteUtils.STATUS_FREE_TEXT.equals(item.getStatus())) {
          d.setChoiceItemName(EnqueteUtils.getSummaryChoiceItemFreeText(
            rundata,
            EnqueteUtils.FLAG_SUMMARY,
            item_id,
            someAnswer,
            enquete));
        } else {
          d.setChoiceItemName(EnqueteUtils.getSummaryChoiceItem(
            rundata,
            item_id,
            someAnswer,
            enquete,
            EnqueteUtils.FLAG_SUMMARY));
        }

        // 同じ項目IDを持つ選択肢の総数を取得する
        SelectQuery<AvzTEnqueteChoiceItem> choicequery =
          Database.query(AvzTEnqueteChoiceItem.class);

        Expression choiceexp =
          ExpressionFactory.matchDbExp(
            AvzTEnqueteChoiceItem.AVZ_TENQUETE_ITEM_PROPERTY
              + "."
              + AvzTEnqueteItem.ITEM_ID_PK_COLUMN,
            item_id);
        Expression choiceexp2 =
          ExpressionFactory.matchExp(
            AvzTEnqueteChoiceItem.ENQUETE_ID_PROPERTY,
            enquete.getEnqueteId());

        choicequery.setQualifier(choiceexp.andExp(choiceexp2));
        ResultList<AvzTEnqueteChoiceItem> choicelist =
          choicequery.getResultList();

        // 項目ID毎の総数
        int Sum = choicelist.size();

        // 項目毎の選択肢数を取得
        SelectQuery<AvzTEnqueteItem> itemquery =
          Database.query(AvzTEnqueteItem.class);

        Expression itemexp =
          ExpressionFactory.matchDbExp(
            AvzTEnqueteItem.ITEM_ID_PK_COLUMN,
            item_id);

        itemquery.setQualifier(itemexp);
        ResultList<AvzTEnqueteItem> itemlist = itemquery.getResultList();

        int choiceSum = 0;
        for (int j = 0; j < itemlist.size(); j++) {
          AvzTEnqueteItem itemNum = itemlist.get(j);
          itemNum.getChoiceItemNum();
          // 項目毎の選択肢数
          choiceSum = item.getChoiceItemNum();
        }

        // 項目÷選択肢数で回答対象者数を取得
        answer_sum = Sum / choiceSum;

        // 回答済みの選択数を取得する
        SelectQuery<AvzTEnqueteChoiceItem> choquery2 =
          Database.query(AvzTEnqueteChoiceItem.class);

        Expression choexp =
          ExpressionFactory.matchDbExp(
            AvzTEnqueteChoiceItem.AVZ_TENQUETE_ITEM_PROPERTY
              + "."
              + AvzTEnqueteItem.ITEM_ID_PK_COLUMN,
            item_id);
        Expression choexp2 =
          ExpressionFactory.matchExp(
            AvzTEnqueteChoiceItem.ENQUETE_ID_PROPERTY,
            enquete.getEnqueteId());
        Expression choexp3 =
          ExpressionFactory.matchExp(
            AvzTEnqueteChoiceItem.RESPONSE_STATUS_PROPERTY,
            EnqueteUtils.RESPONSE_STATUS_AFTER);

        choquery2.setQualifier(choexp.andExp(choexp2).andExp(choexp3));
        ResultList<AvzTEnqueteChoiceItem> cholist = choquery2.getResultList();

        int a = cholist.size();
        if (cholist.size() != 0) {

          // 項目÷選択肢数で回答者数を取得
          selected_answer_sum = cholist.size() / choiceSum;

        } else {
          selected_answer_sum = 0;
        }

        itemresults.add(d);

      }

      return enquete;

    } catch (ALPageNotFoundException pageNotFound) {
      throw pageNotFound;
    }
  }

  /**
   * ResultData に値を格納して返します。（詳細データ） <BR>
   * 
   * @param obj
   * @return
   * @see com.aimluck.eip.common.ALAbstractSelectData#getResultDataDetail(java.lang.Object)
   */
  @Override
  protected Object getResultDataDetail(AvzTEnquete obj) {
    try {
      AvzTEnquete record = obj;
      EnqueteSummaryListResultData rd = new EnqueteSummaryListResultData();
      rd.initField();
      rd.setEnqueteId(record.getEnqueteId());
      rd.setName(record.getName());
      rd.setComment(record.getComment());
      ALStringField creatername = new ALStringField();
      creatername.setValue(ALEipUtils.getUserFullName(record.getCreaterId()));
      rd.setCreaterName(creatername);
      rd.setMethod(record.getPublicMethod());
      return rd;
    } catch (Exception ex) {
      logger.error("Exception", ex);
      return null;
    }
  }

  /**
   * @return
   * @see com.aimluck.eip.common.ALAbstractSelectData#getColumnMap()
   */
  @Override
  protected Attributes getColumnMap() {
    return null;
  }

  /**
   * アンケート回答対象者数を取得します。 <BR>
   * 
   * @return
   */

  public int getAnswerSum() {
    return answer_sum;
  }

  /**
   * アンケート回答者数を取得します。 <BR>
   * 
   * @return
   */

  public int getSelectedAnswerSum() {
    return selected_answer_sum;
  }

  /**
   * アンケート項目・選択肢取得リストを取得します。 <BR>
   * 
   * @return
   */

  public List getItemResults() {
    return itemresults;
  }

}
