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

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

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.ALEipConstants;
import com.aimluck.eip.common.ALPageNotFoundException;
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;

/**
 * LunchOrderのユーティリティクラスです。 <BR>
 * 
 */
public class LunchOrderUtils {

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

  /**
   * AvzTLunchOrder オブジェクトモデルを取得します。 <BR>
   * 
   * @param rundata
   * @param context
   * @return
   */
  public static AvzTLunchOrder getAvzTLunchOrder(RunData rundata,
      Context context) throws ALPageNotFoundException {
    String avzTLunchOrderMapId =
      ALEipUtils.getTemp(rundata, context, ALEipConstants.ENTITY_ID);
    try {

      AvzTLunchOrder avzTLunchOrder =
        getAvzTLunchOrder(rundata, context, Integer
          .valueOf(avzTLunchOrderMapId));
      return avzTLunchOrder;
    } catch (ALPageNotFoundException pageNotFound) {
      throw pageNotFound;
    } catch (Exception ex) {
      logger.error("Exception", ex);
      return null;
    }
  }

  /**
   * AvzTLunchOrder オブジェクトモデルを取得します。 <BR>
   * 
   * @param rundata
   * @param context
   * @return
   */
  public static AvzTLunchOrder getAvzTLunchOrder(RunData rundata,
      Context context, Integer avzTLunchOrderMapId)
      throws ALPageNotFoundException {

    try {
      SelectQuery<AvzTLunchOrder> query = Database.query(AvzTLunchOrder.class);
      Expression exp =
        ExpressionFactory.matchDbExp(
          AvzTLunchOrder.ORDER_MAP_ID_PK_COLUMN,
          avzTLunchOrderMapId);

      query.setQualifier(exp);
      ResultList<AvzTLunchOrder> avzTLunchOrders = query.getResultList();

      return (avzTLunchOrders.get(0));

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

  /**
   * AvzTLunchOrderItem オブジェクトモデルを取得します。 <BR>
   * 
   * @param rundata
   * @param context
   * @return
   */
  // public static AvzTLunchOrderItem getAvzTLunchOrderItem(RunData rundata,
  // Context context) throws ALPageNotFoundException {
  // String LunchOrderMapId =
  // ALEipUtils.getTemp(rundata, context, ALEipConstants.ENTITY_ID);
  // try {
  //
  // AvzTLunchOrderItem avzTLunchOrderItem =
  // getAvzTLunchOrderItem(rundata, context, Integer
  // .valueOf(LunchOrderMapId));
  // return avzTLunchOrderItem;
  // } catch (ALPageNotFoundException pageNotFound) {
  // throw pageNotFound;
  // } catch (Exception ex) {
  // logger.error("Exception", ex);
  // return null;
  // }
  // }
  /**
   * AvzTLunchOrderItem オブジェクトモデルを取得します。 <BR>
   * 
   * @param rundata
   * @param context
   * @return
   */
  // public static AvzTLunchOrderItem getAvzTLunchOrderItem(RunData rundata,
  // Context context, Integer avzTLunchOrderMapId)
  // throws ALPageNotFoundException {
  //
  // try {
  //
  // DataContext dataContext =
  // DatabaseOrmService.getInstance().getDataContext();
  // SelectQuery<AvzTLunchOrderItem> query =
  // Database.query(AvzTLunchOrderItem.class);
  // Expression exp =
  // ExpressionFactory.matchDbExp(
  // AvzTLunchOrderItem.ORDER_MAP_ID_PROPERTY,
  // avzTLunchOrderMapId);
  //
  // query.setQualifier(exp);
  // List avzTLunchOrderItems = dataContext.performQuery(query);
  //
  // return ((AvzTLunchOrderItem) avzTLunchOrderItems);
  //
  // } catch (Exception ex) {
  // logger.error("Exception", ex);
  // return null;
  // }
  // }
  /**
   * 弁当屋のコメントを取得します。 <BR>
   * 
   * @param int
   *            storeMapID
   * @return
   */
  public static String getStoreComment(int storeMapId) {// 弁当屋のコメントを取得するメソッド

    Expression exp = ExpressionFactory.matchDbExp(// 弁当屋ごとの条件
      AvzTLunchOrder.ORDER_MAP_ID_PK_COLUMN,
      storeMapId);

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

    ResultList<AvzTLunchOrder> list = query.getResultList();

    AvzTLunchOrder record = list.get(0);

    String storeComment = record.getComment();

    return storeComment;
  }

  /**
   * 注文先弁当屋の総注文数を取得します。 <BR>
   * 
   * @param int
   *            storeMapID
   * @return
   */
  public static int getTotalSum(int storeMapId) {// 選択された注文先弁当屋の総注文数を取得
    int totalSum = 0;

    Expression exp =
      ExpressionFactory.matchDbExp(// 弁当屋ごとの条件
        AvzTLunchUserOrder.TO_AVZ_TLUNCH_ORDER_ITEM_PROPERTY
          + "."
          + AvzTLunchOrderItem.TO_AVZ_TLUNCH_ORDER_PROPERTY
          + "."
          + AvzTLunchOrder.ORDER_MAP_ID_PK_COLUMN,
        storeMapId);

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

    ResultList<AvzTLunchUserOrder> list = query.getResultList();

    int length = list.size();

    for (int i = 0; i < length; i++) {
      AvzTLunchUserOrder record = list.get(i);
      totalSum = totalSum + record.getOrderAmount();
    }
    return totalSum;
  }

  /**
   * 注文先弁当屋の総注文金額を取得します。 <BR>
   * 
   * @param int
   *            storeMapID
   * @return
   */
  public static int getTotalPrice(int storeMapId) {// 選択された注文先弁当屋の総注文金額を取得
    int totalPrice = 0;
    Expression exp =
      ExpressionFactory.matchDbExp(// 弁当屋ごとの条件
        AvzTLunchUserOrder.TO_AVZ_TLUNCH_ORDER_ITEM_PROPERTY
          + "."
          + AvzTLunchOrderItem.TO_AVZ_TLUNCH_ORDER_PROPERTY
          + "."
          + AvzTLunchOrder.ORDER_MAP_ID_PK_COLUMN,
        storeMapId);

    SelectQuery<AvzTLunchUserOrder> query =
      Database.query(AvzTLunchUserOrder.class, exp);
    ResultList<AvzTLunchUserOrder> list = query.getResultList();

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

      AvzTLunchUserOrder record = list.get(i);

      // int itemId = record.getToAvzTLunchOrderItem().getItemId();
      int itemPrice = record.getToAvzTLunchOrderItem().getPrice();
      totalPrice = totalPrice + (record.getOrderAmount() * itemPrice);
    }
    return totalPrice;
  }

  /**
   * 前日分の注文を消去します。 <BR>
   * 
   * @return
   */
  public static void deleteOrder() {// 前日分の注文を消去するメソッド
    try {

      Calendar cal = Calendar.getInstance(); // 現在時刻取得

      SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
      int nowdate = Integer.parseInt(simpleDateFormat.format(cal.getTime()));

      SelectQuery<AvzTLunchUserOrder> query =
        Database.query(AvzTLunchUserOrder.class);

      ResultList<AvzTLunchUserOrder> list = query.getResultList();// 注文データを取得

      int size = list.size();

      if (size > 0) {// 注文データが存在する場合にのみ削除の判定

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

          AvzTLunchUserOrder avzTLunchUserOrder = list.get(i);
          Date orderDate = avzTLunchUserOrder.getOrderDate();
          SimpleDateFormat simpleDateFormatAfter =
            new SimpleDateFormat("yyyyMMdd");
          int orderdate =
            Integer.parseInt(simpleDateFormatAfter.format(orderDate));

          if (nowdate == orderdate) {

          } else {
            Database.delete(avzTLunchUserOrder);
            Database.commit();
          }

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

  /**
   * 注文表で表示する属性を取得します。 <BR>
   * 
   * @return
   */
  public static String getStatus(int storeMapId) {// 注文表で表示する属性を取得

    String status;

    Expression exp = ExpressionFactory.matchDbExp(// 弁当屋ごとの条件
      AvzTLunchOrder.ORDER_MAP_ID_PK_COLUMN,
      storeMapId);

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

    ResultList<AvzTLunchOrder> list = getStatusQuery.getResultList();

    AvzTLunchOrder record = list.get(0);

    if ((record.getMinStatus().equals("P"))) {// 最低注文”価格”の設定がある場合

      int min_price = record.getMinPlice();// 最低注文価格
      int order_price = 0;// 実際注文されている合計金額用の変数

      Expression exp01 =
        ExpressionFactory.matchDbExp(
          AvzTLunchUserOrder.TO_AVZ_TLUNCH_ORDER_ITEM_PROPERTY
            + "."
            + AvzTLunchOrderItem.TO_AVZ_TLUNCH_ORDER_PROPERTY
            + "."
            + AvzTLunchOrder.ORDER_MAP_ID_PK_COLUMN,
          storeMapId);
      SelectQuery<AvzTLunchUserOrder> query01 =
        Database.query(AvzTLunchUserOrder.class, exp01);

      ResultList<AvzTLunchUserOrder> orderlist = query01.getResultList();

      // ↓弁当屋ごとに登録されているアイテム（弁当）をとりだして、アイテムの注文状況を検索
      for (int i = 0; i < orderlist.size(); i++) {
        AvzTLunchUserOrder avzTLunchUserOrder = orderlist.get(i);

        int itemPrice = avzTLunchUserOrder.getToAvzTLunchOrderItem().getPrice();
        order_price =
          order_price + (avzTLunchUserOrder.getOrderAmount() * itemPrice);
      }

      if (min_price > order_price) { // 最低注文金額未達の場合
        status = "price_NotAchievement";// 備考表示内容フラグ設定（velocityで表示振り分けに使用）
      } else { // 最低注文金額達成の場合
        status = "price_Achievement";// 備考表示内容フラグ設定（velocityで表示振り分けに使用）
      }

    } else if (record.getMinStatus().equals("N")) {// 最低注文”数”の設定がある場合

      int min_num = record.getMinNum();// 最低注文数
      int order_amount = 0;// 実際注文されている合計数用の変数

      Expression exp1 =
        ExpressionFactory.matchDbExp(// 弁当屋ごとの条件
          AvzTLunchUserOrder.TO_AVZ_TLUNCH_ORDER_ITEM_PROPERTY
            + "."
            + AvzTLunchOrderItem.TO_AVZ_TLUNCH_ORDER_PROPERTY
            + "."
            + AvzTLunchOrder.ORDER_MAP_ID_PK_COLUMN,
          storeMapId);
      Expression exp2 =
        ExpressionFactory.matchExp(// 注文数にカウントするアイテムだけの条件（※"1"はカウントする"0"はカウントしない）
          AvzTLunchUserOrder.TO_AVZ_TLUNCH_ORDER_ITEM_PROPERTY
            + "."
            + AvzTLunchOrderItem.MIN_ORDER_FLAG_PROPERTY,
          1);

      SelectQuery<AvzTLunchUserOrder> query =
        Database.query(AvzTLunchUserOrder.class, exp1.andExp(exp2));

      ResultList<AvzTLunchUserOrder> orderlist = query.getResultList();

      for (int i = 0; i < orderlist.size(); i++) {// 注文数だけを取り出していく
        AvzTLunchUserOrder avzTLunchUserOrder = orderlist.get(i);
        order_amount = avzTLunchUserOrder.getOrderAmount() + order_amount;
      }

      if (min_num > order_amount) {// 最低注文数未達の場合
        status = "amount_NotAchievement";// 備考表示内容フラグ設定（velocityで表示振り分けに使用）
      } else {// 最低注文数達成の場合
        status = "amount_Achievement";// 備考表示内容フラグ設定（velocityで表示振り分けに使用）
      }

    } else {// 特に条件なしの場合
      status = "condition none";// 備考表示内容フラグ設定（velocityで表示振り分けに使用）
    }
    return status;
  }

  /**
   * 弁当屋ごとに登録されている商品の数（リストの長さ）を取得します。 <BR>
   * 
   * @return
   */
  public static int getOrderItemLength(int storeMapId) {// 弁当屋ごとに登録されている商品の数（リストの長さ）

    Expression exp =
      ExpressionFactory.matchDbExp(
        AvzTLunchOrder.ORDER_MAP_ID_PK_COLUMN,
        storeMapId);

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

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

    int length = list.size();

    return length;
  }

  public static String getStoreName(int storeMapId) {// storeMapIdから弁当屋名を取得するメソッド

    String storeName = null;

    Expression exp =
      ExpressionFactory.matchDbExp(
        AvzTLunchOrder.ORDER_MAP_ID_PK_COLUMN,
        storeMapId);

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

    ResultList<AvzTLunchOrder> name = query.getResultList();

    AvzTLunchOrder nameRecord = name.get(0);

    if (name.size() == 0) {
      return null;
    }
    storeName = nameRecord.getStoreName();
    return storeName;
  }

  /**
   * ItemIdから商品名を取得します。 <BR>
   * 
   * @return
   */
  public static String getItemName(int itemId) {// ItemIdから商品名を取得するメソッド

    String itemName = null;

    Expression exp =
      ExpressionFactory
        .matchDbExp(AvzTLunchOrderItem.ITEM_ID_PK_COLUMN, itemId);

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

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

    AvzTLunchOrderItem itemRecord = items.get(0);

    if (items.size() == 0) {
      return null;
    }
    itemName = itemRecord.getItemTitle();
    return itemName;
  }

  /**
   * 選択された弁当屋ごとにUserIdからユーザーが注文している全商品の合計金額を取得します。 <BR>
   * 
   * @return
   */
  public static int getTotalPrice(int userId, int orderMapId) {// 選択された弁当屋ごとにUserIdからユーザーが注文している全商品の合計金額を取得するメソッド

    int totalPrice = 0;
    Expression exp01 =
      ExpressionFactory.matchExp(AvzTLunchUserOrder.USER_ID_PROPERTY, userId);

    Expression exp02 =
      ExpressionFactory.matchDbExp(
        AvzTLunchUserOrder.TO_AVZ_TLUNCH_ORDER_ITEM_PROPERTY
          + "."
          + AvzTLunchOrderItem.TO_AVZ_TLUNCH_ORDER_PROPERTY
          + "."
          + AvzTLunchOrder.ORDER_MAP_ID_PK_COLUMN,
        orderMapId);

    SelectQuery<AvzTLunchUserOrder> query =
      Database.query(AvzTLunchUserOrder.class, exp01.andExp(exp02));

    ResultList<AvzTLunchUserOrder> uPriceList = query.getResultList();

    int length = uPriceList.size();

    for (int i = 0; i < length; i++) {

      AvzTLunchUserOrder uPliceRecord = uPriceList.get(i);

      int itemId = uPliceRecord.getToAvzTLunchOrderItem().getItemId();
      int order_amount = uPliceRecord.getOrderAmount();
      int itemPrice = uPliceRecord.getToAvzTLunchOrderItem().getPrice();

      totalPrice = totalPrice + (order_amount * itemPrice);
    }
    return totalPrice;
  }
}
