/*
 * 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.Date;
import java.util.List;

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.cayenne.om.portlet.AvzTLunchUserOrder;
import com.aimluck.eip.common.ALAbstractFormData;
import com.aimluck.eip.common.ALDBErrorException;
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 LunchOrderConfirmationFormData extends ALAbstractFormData {

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

  /** シーケンスID */
  // private ALNumberField id;
  /** 注文商品ID * */
  // private ALNumberField item_id;
  /** 注文商品個数 * */
  // private ALNumberField order_amount;
  /** 注文者ID */
  // private ALNumberField user_id;
  /** 注文時刻 */
  // private ALDateTimeField order_date;
  /**
   * init
   * 
   * @param action
   * @param rundata
   * @param context
   * @see com.aimluck.eip.common.ALAbstractFormData#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>
   * 
   * @see com.aimluck.eip.common.ALData#initField()
   */
  public void initField() {
    // id = new ALNumberField();
    // item_id = new ALNumberField();
    // order_amount = new ALNumberField();
    // user_id = new ALNumberField();
    // order_date = new ALDateTimeField();
  }

  /**
   * セッションから取り出した値をデータベースに格納します。 <BR>
   * 
   * @param rundata
   * @param context
   * @param msgList
   * @return TRUE 成功 FALSE 失敗
   * @see com.aimluck.eip.common.ALAbstractFormData#insertFormData(org.apache.turbine.util.RunData,
   *      org.apache.velocity.context.Context, java.util.ArrayList)
   */
  public boolean insertFormData(RunData rundata, Context context) {
    try {
      // 注文先の注文表のフィールド数を決定するための条件
      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);

      ResultList<AvzTLunchOrderItem> itemList = query.getResultList();

      // セッションに保存している注文数を取得
      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());

        AvzTLunchOrderItem avzTLuchOrderItem = itemList.get(i);
        int item_id = avzTLuchOrderItem.getItemId();

        // 新規オブジェクトモデル

        if (orderSum != 0) {// 注文数が0個だったらDBに登録しない

          AvzTLunchUserOrder avzTLunchUserOrder =
            Database.create(AvzTLunchUserOrder.class);
          // 注文商品ID
          avzTLunchUserOrder.setItemId(item_id);

          // 注文ユーザーID
          avzTLunchUserOrder.setUserId(ALEipUtils.getUserId(rundata));

          // 注文数
          avzTLunchUserOrder.setOrderAmount(orderSum);
          // 注文日
          Date now = new Date();
          avzTLunchUserOrder.setOrderDate(now);

          // 注文内容を登録
          Database.commit();
        }
      }

    } catch (Exception ex) {
      Database.rollback();
      logger.error("Exception", ex);
      return false;
    }
    clearLunchOrderSession(rundata, context);
    return true;
  }

  // セッション開放
  private void clearLunchOrderSession(RunData rundata, Context context) {
    List<String> list = new ArrayList<String>();
    // エンティティIDの初期化
    list.add("entityid");
    // セッションに保存しているストアID
    list.add("com.aimluck.eip.lunchorder.storeMapIdKey");
    // セッションに保存している注文数
    list.add("com.aimluck.eip.lunchorder.orderSumKey");

    ALEipUtils.removeTemp(rundata, context, list);
  }

  @Override
  protected void setValidator() {
  }

  @Override
  protected boolean validate(List<String> msgList) {
    return (msgList.size() == 0);
  }

  @Override
  protected boolean loadFormData(RunData rundata, Context context,
      List<String> msgList) {
    return true;
  }

  @Override
  protected boolean deleteFormData(RunData rundata, Context context,
      List<String> msgList) {
    return true;
  }

  @Override
  protected boolean updateFormData(RunData rundata, Context context,
      List<String> msgList) {
    return true;
  }

  @Override
  protected boolean insertFormData(RunData rundata, Context context,
      List<String> msgList) {
    return true;
  }
}
