/*
 * 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.lunchorder;

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.eip.cayenne.om.portlet.AvzTLunchOrder;
import com.aimluck.eip.cayenne.om.portlet.AvzTLunchOrderItem;
import com.aimluck.eip.common.ALAbstractSelectData;
import com.aimluck.eip.common.ALDBErrorException;
import com.aimluck.eip.common.ALData;
import com.aimluck.eip.common.ALPageNotFoundException;
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;

/**
 * 注文表データを管理するクラスです。 <BR>
 * 
 */
public class LunchOrderConfirmationSelectData extends
    ALAbstractSelectData<AvzTLunchOrderItem, Object> implements ALData {

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

  /** 注文数 */
  private int orderSum;

  /** 選択された注文先弁当屋名 * */
  private String storeName;

  /** 注文数リスト * */
  private List<Object> orderSumList;

  /** 注文合計金額 * */
  private int totalPrice;

  private int count = 0;

  /**
   * 
   * @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<AvzTLunchOrderItem> selectList(RunData rundata,
      Context context) {
    try {

      SelectQuery<AvzTLunchOrderItem> query = getSelectQuery(rundata, context);
      buildSelectQueryForListView(query);
      query.orderAscending("itemTitle");
      ResultList<AvzTLunchOrderItem> list = query.getResultList();

      orderSumList = new ArrayList<Object>();
      String orderAmount =
        new String(ALEipUtils.getTemp(
          rundata,
          context,
          "com.aimluck.eip.lunchorder.orderSumKey"));

      int charLength = orderAmount.length();// セッションから取り出した値を配列に入れていく処理
      String orderAmountList = orderAmount.substring(1, charLength - 1);// 頭の"["と末尾の"]"を除く
      String[] IndividualOrderAmount = orderAmountList.split(",");// ","で区切る
      int listSize = IndividualOrderAmount.length;
      for (int i = 0; i < listSize; i++) {
        int orderSum = Integer.parseInt(IndividualOrderAmount[i].trim());
        orderSumList.add(orderSum);// 配列に入れる
      }

      return list;

    } catch (Exception ex) {
      logger.error("Exception", ex);
      return null;
    }

  }

  /**
   * 検索条件を設定した SelectQuery を返します。 <BR>
   * 
   * @param rundata
   * @param context
   * @return
   */
  private SelectQuery<AvzTLunchOrderItem> getSelectQuery(RunData rundata,
      Context context) {

    Expression exp =
      ExpressionFactory.matchDbExp(
        AvzTLunchOrderItem.TO_AVZ_TLUNCH_ORDER_PROPERTY
          + "."
          + AvzTLunchOrder.ORDER_MAP_ID_PK_COLUMN,
        Integer.parseInt(ALEipUtils.getTemp(
          rundata,
          context,
          "com.aimluck.eip.lunchorder.storeMapIdKey")));

    SelectQuery<AvzTLunchOrderItem> query =
      Database.query(AvzTLunchOrderItem.class, exp);

    return query;
  }

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

      AvzTLunchOrderItem itemRecord = obj;

      LunchOrderConfirmationResultData rd =
        new LunchOrderConfirmationResultData();// インスタンス生成

      rd.initField(); // オブジェクトのフィールドを初期化
      rd.setItemId(itemRecord.getItemId());// 商品のID
      rd.setItemName(itemRecord.getItemTitle());// 弁当名
      rd.setSubTotalPrice(itemRecord.getPrice() * getOrderSum(count));// （小計）
      rd.setComment(itemRecord.getComment());// 弁当に対するコメント
      rd.setOrderSum(getOrderSum(count));// 注文数

      totalPrice = totalPrice + (itemRecord.getPrice() * getOrderSum(count));// 合計注文数用変数に小計を足していく

      count = count + 1; // 配列インデックス用のインクリメント処理

      return rd;

    } catch (Exception ex) {
      logger.error("Exception", ex);
      return null;
    }
  }

  /**
   * @return
   * @velocityで合計金額取得メソッド
   */
  public int getTotalPrice() {
    return totalPrice;
  }

  /**
   * @return
   * @velocityで店舗名取得メソッド
   */
  public String getStoreName() {
    return storeName;
  }

  /**
   * @return
   * @velocityで合計注文数取得メソッド
   */
  public int getOrderSum(int i) {
    orderSum = Integer.parseInt(orderSumList.get(i).toString());
    return orderSum;
  }

  /**
   * 詳細データを取得します。 <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 Object selectDetail(RunData rundata, Context context)
      throws ALPageNotFoundException {
    return null;
  }

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

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