package com.aimluck.eip.enquete;

import java.util.ArrayList;
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;

public class EnqueteSummaryDetailSelectData extends
    ALAbstractSelectData<AvzTEnquete, AvzTEnquete> implements ALData {

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

  /** 項目名 */
  private ALStringField itemName;

  /** 状態(複数選択可不可) */
  private String status;

  /** 詳細リスト */
  private ArrayList<EnqueteChoiceItemRecordData> detailList;

  /** アンケートID */
  private long enqueteId;

  /**
   * 
   * @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 {
      // ENTITY_IDは、画面から渡されてくるｉｔｅｍＩｄ
      // ENTITY_IDに一致するものをselect
      SelectQuery<AvzTEnqueteItem> query =
        Database.query(AvzTEnqueteItem.class);
      Expression exp =
        ExpressionFactory.matchDbExp(
          AvzTEnqueteItem.ITEM_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();

      // 選択項目数
      int cNum = 0;

      ALStringField record = new ALStringField();
      // 1件しか取ってこれないはずなので、break
      for (int i = 0; i < list.size(); i++) {
        AvzTEnqueteItem item = list.get(i);
        // 項目タイトルをセット
        record.setValue(item.getItemTitle());
        itemName = record;
        // 回答方法をセット
        status = item.getStatus();
        // アンケートID
        enqueteId = item.getEnqueteId();
        // 選択項目数
        cNum = item.getChoiceItemNum();
        break;
      }

      AvzTEnquete enquete =
        EnqueteUtils.getAvzTEnqueteSummaryDetail(rundata, context, enqueteId);

      detailList = new ArrayList<EnqueteChoiceItemRecordData>();
      if (EnqueteUtils.STATUS_FREE_TEXT.equals(status)) {
        // フリーテキスト用取得メソッド
        freeTextChoiceItem(rundata, context);
      } else {
        for (int i = 1; i <= cNum; i++) {
          // その他用取得メソッド
          selectChoiceItem(rundata, context, i);
        }
      }

      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;
      EnqueteSummaryDetailResultData rd = new EnqueteSummaryDetailResultData();
      rd.initField();
      rd.setName(record.getName());
      rd.setMethod(record.getPublicMethod());
      rd.setItemName(itemName);
      rd.setStatus(status);
      rd.setDetailList(detailList);
      rd.setEnqueteId(enqueteId);
      return rd;
    } catch (Exception ex) {
      logger.error("Exception", ex);
      return null;
    }
  }

  // フリーテキスト用取得メソッド
  public void freeTextChoiceItem(RunData rundata, Context context) {
    SelectQuery<AvzTEnqueteChoiceItem> answerquery =
      Database.query(AvzTEnqueteChoiceItem.class);

    Expression answerExp =
      ExpressionFactory.matchDbExp(
        AvzTEnqueteChoiceItem.AVZ_TENQUETE_ITEM_PROPERTY
          + "."
          + AvzTEnqueteItem.ITEM_ID_PK_COLUMN,
        ALEipUtils.getTemp(rundata, context, ALEipConstants.ENTITY_ID));
    answerExp =
      answerExp.andExp(ExpressionFactory.matchExp(
        AvzTEnqueteChoiceItem.STATUS_PROPERTY,
        EnqueteUtils.STATUS_SELECT));
    answerExp =
      answerExp.andExp(ExpressionFactory.matchExp(
        AvzTEnqueteChoiceItem.RESPONSE_STATUS_PROPERTY,
        EnqueteUtils.RESPONSE_STATUS_AFTER));

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

    // 人数分繰り返し
    for (int i = 0; i < getAnswer.size(); i++) {
      AvzTEnqueteChoiceItem choice = getAnswer.get(i);
      EnqueteChoiceItemRecordData record = new EnqueteChoiceItemRecordData();
      ALStringField answer = new ALStringField();
      answer.setValue(ALEipUtils.getUserFullName(choice.getAnswerId()));
      // 回答者
      record.setAnswer(answer);
      ALStringField title = new ALStringField();

      if ("".equals(choice.getChoiceItemTitle())) {
        // 空で「回答する」を押した場合
        title.setValue("記入なし");
      } else {
        // 空でなかった場合
        title.setValue(choice.getChoiceItemTitle());
      }
      record.setChoiceItemTitle(title);
      detailList.add(record);
    }
  }

  // 単一・複数選択用取得メソッド
  public void selectChoiceItem(RunData rundata, Context context, int num) {
    SelectQuery<AvzTEnqueteChoiceItem> answerquery =
      Database.query(AvzTEnqueteChoiceItem.class);

    Expression answerExp =
      ExpressionFactory.matchDbExp(
        AvzTEnqueteChoiceItem.AVZ_TENQUETE_ITEM_PROPERTY
          + "."
          + AvzTEnqueteItem.ITEM_ID_PK_COLUMN,
        ALEipUtils.getTemp(rundata, context, ALEipConstants.ENTITY_ID));
    answerExp =
      answerExp.andExp(ExpressionFactory.matchExp(
        AvzTEnqueteChoiceItem.STATUS_PROPERTY,
        EnqueteUtils.STATUS_SELECT));
    answerExp =
      answerExp.andExp(ExpressionFactory.matchExp(
        AvzTEnqueteChoiceItem.RESPONSE_STATUS_PROPERTY,
        EnqueteUtils.RESPONSE_STATUS_AFTER));
    answerExp =
      answerExp.andExp(ExpressionFactory.matchExp(
        AvzTEnqueteChoiceItem.CHOICE_ITEM_NUMBER_PROPERTY,
        num));

    answerquery.setQualifier(answerExp);
    ResultList<AvzTEnqueteChoiceItem> getAnswer = answerquery.getResultList();
    EnqueteChoiceItemRecordData record = new EnqueteChoiceItemRecordData();
    // 回答者リスト
    ArrayList<ALStringField> answerList = new ArrayList<ALStringField>();
    if (getAnswer.size() != 0) {
      for (int i = 0; i < getAnswer.size(); i++) {
        AvzTEnqueteChoiceItem choice = getAnswer.get(i);
        if (i == 0) {
          // タイトルと項目番号は、1回setすればよいため
          // 選択項目タイトル
          ALStringField title = new ALStringField();
          title.setValue(choice.getChoiceItemTitle());
          record.setChoiceItemTitle(title);
          // 選択項目番号
          record.setChoiceItemNumber(choice.getChoiceItemNumber());
          // 回答者
          ALStringField answer = new ALStringField();
          answer.setValue(ALEipUtils.getUserFullName(choice.getAnswerId()));
          answerList.add(answer);
        } else {
          // 回答者
          ALStringField answer = new ALStringField();
          answer.setValue(ALEipUtils.getUserFullName(choice.getAnswerId()));
          answerList.add(answer);
        }
      }
      record.setAnswerList(answerList);
      detailList.add(record);
    }
  }

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

}
