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

import java.util.Calendar;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.cayenne.access.DataContext;
import org.apache.cayenne.exp.Expression;
import org.apache.cayenne.exp.ExpressionFactory;
import org.apache.cayenne.query.SelectQuery;
import org.apache.jetspeed.services.logging.JetspeedLogFactoryService;
import org.apache.jetspeed.services.logging.JetspeedLogger;
import org.apache.turbine.util.RunData;
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.orm.DatabaseOrmService;

/**
 * 注文表（集計）ファイル出力を取り扱うクラスです
 */
public class LunchOrderCsvExportScreen extends ALCSVScreen {
  /**
   * logger
   */
  private static final JetspeedLogger logger = JetspeedLogFactoryService
      .getLogger(LunchOrderCsvExportScreen.class.getName());

  /**
   * HTTP コンテンツタイプ
   * 
   * @see org.apache.turbine.modules.screens.RawScreen#getContentType(org.apache.turbine.util.RunData)
   */
  @Override
  protected String getContentType(RunData rundata) {
    return "application/octet-stream";
  }

  /**
   * 出力ファイル名（接頭辞）
   */
  public static String FILE_NAME = "";

  /**
   * 拡張子名
   */
  public static final String FILE_EXTENTION = ".csv";

  /**
   * CSVデータ改行値
   */
  public static final String LINE_SEPARATOR = System
      .getProperty("line.separator");

  /**
   * CSVデータ区切り文字
   */
  public static final String COLOMN_SEPARATOR = ",";

  @Override
  protected void doOutput(RunData rundata) throws Exception {
    ServletOutputStream out = null;

    try {

      Calendar today = Calendar.getInstance();
      String result = getCSVString(rundata);
      FILE_NAME = rundata.getParameters().getString("store_name") + "注文表" + "-"
          + today.get(Calendar.YEAR) + "-" + (today.get(Calendar.MONTH) + 1)
          + "-" + today.get(Calendar.DAY_OF_MONTH) + FILE_EXTENTION;
      String fileName = new String(FILE_NAME.getBytes("Shift_JIS"),
          "ISO-8859-1");

      HttpServletResponse response = rundata.getResponse();
      // ファイル名の送信(attachment部分をinlineに変更すればインライン表示)
      response.setHeader("Content-disposition", "attachment; filename=\""
          + fileName + "\"");
      response.setHeader("Cache-Control", "no-cache");
      response.setHeader("Pragma", "No-cache");

      // ファイル内容の出力
      out = response.getOutputStream();
      out.write(result.getBytes("Shift_JIS"));
      out.flush();
      out.close();
    } catch (Exception e) {
      logger.error("[ERROR]", e);
    }

  }

  /**
   * CSV文字列取り出し用メソッド。<br />
   * CSV文字列を返します。
   * 
   * @param rundata
   *            RunData
   * @return
   */
  protected String getCSVString(RunData rundata) {
    StringBuffer sb = new StringBuffer();
    // ヘッダライン設定
    makeHeaderLine(sb);

    DataContext dataContext = DatabaseOrmService.getInstance().getDataContext();

    String storeMapId = rundata.getParameters()
        .getString("target_order_map_id");// 選択された弁当屋IDを親クラスのメソッドにて取得

    int orderMapId = Integer.valueOf(storeMapId);

    Expression exp1 = ExpressionFactory.matchDbExp(
        AvzTLunchOrderItem.TO_AVZ_TLUNCH_ORDER_PROPERTY + "."
            + AvzTLunchOrder.ORDER_MAP_ID_PK_COLUMN, orderMapId);
    SelectQuery query = new SelectQuery(AvzTLunchOrderItem.class, exp1);
    List list = dataContext.performQuery(query);

    int recNum = list.size();

    for (int j = 0; j < recNum; j++) {
      AvzTLunchOrderItem avzTLunchOrderItem = (AvzTLunchOrderItem) list.get(j);

      // 商品名
      sb.append("\"" + avzTLunchOrderItem.getItemTitle() + "\""
          + COLOMN_SEPARATOR);
      // 商品Id
      int itemId = avzTLunchOrderItem.getItemId();

      // 注文数
      Expression exp2 = ExpressionFactory.matchDbExp(// 選択された弁当屋に対する注文商品を検索するための条件
          AvzTLunchUserOrder.TO_AVZ_TLUNCH_ORDER_ITEM_PROPERTY + "."
              + AvzTLunchOrderItem.ITEM_ID_PK_COLUMN, itemId);
      SelectQuery orderItemquery = new SelectQuery(AvzTLunchUserOrder.class,
          exp2);
      List orderItemList = dataContext.performQuery(orderItemquery);// query実行

      int orderAmount = 0;

      for (int i = 0; i < orderItemList.size(); i++) {
        AvzTLunchUserOrder atzLunchUserOrder = (AvzTLunchUserOrder) orderItemList
            .get(i);
        orderAmount = orderAmount + atzLunchUserOrder.getOrderAmount();// 注文数を変数に入れていく
      }
      sb.append("\"" + orderAmount + "\"" + COLOMN_SEPARATOR);

      // 小計金額
      int itemPrice = avzTLunchOrderItem.getPrice();// 弁当の単価を変数に入れる

      itemPrice = orderAmount * itemPrice;// 弁当ごとの小計金額変数に入れる
      sb.append("\"" + itemPrice + "\"" + COLOMN_SEPARATOR);
      sb.append(LINE_SEPARATOR);
    }

    // 生成文字列 デバック用出力
    logger.debug(sb.toString());

    return sb.toString();
  }

  protected String getFileName() {

    return null;
  }

  /**
   * CSVのヘッダ情報を生成します。
   * 
   * @param sb
   *            StringBuffer
   */
  private void makeHeaderLine(StringBuffer sb) {
    sb.append("\"商品名\"" + COLOMN_SEPARATOR);
    sb.append("\"注文数\"" + COLOMN_SEPARATOR);
    sb.append("\"小計金額\"");
    sb.append(LINE_SEPARATOR);
  }
}
