package com.aimluck.eip.genka;

import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

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

import jp.co.imtt.businesssystem.common.IMXlsWriter;
import org.apache.turbine.util.RunData;
import org.apache.velocity.context.Context;
import org.apache.cayenne.DataRow;
import org.apache.cayenne.access.DataContext;
import org.apache.cayenne.query.SQLTemplate;
import org.apache.jetspeed.services.logging.JetspeedLogFactoryService;
import org.apache.jetspeed.services.logging.JetspeedLogger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import com.aimluck.eip.cayenne.om.portlet.ImwTExtTimecardDetail;
import com.aimluck.eip.common.ALDBErrorException;
import com.aimluck.eip.orm.DatabaseOrmService;

public class ProfitXlsWriter extends IMXlsWriter {
  
  /** logger */
  private static final JetspeedLogger logger = JetspeedLogFactoryService
      .getLogger(ProfitXlsWriter.class.getName());  

  public static final String FILE_NAME = "プロジェクト採算表";
  private static final String SHEET_NAME = "";
  private static final String TEMPLATE_NAME  = "template_profit";
  
  public ProfitXlsWriter(RunData rundata){
    // テンプレートファイル名をセット
    setTemplateName(TEMPLATE_NAME);
    // シート名をセット
    setSheetName(SHEET_NAME);
    // 出力ファイル名をセット
    try{
//      SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
//      SimpleDateFormat bookFormat = new SimpleDateFormat("yyMMdd");
//      Calendar startPeriod = Calendar.getInstance();
//      startPeriod.setTime(dateFormat.parse(getCompanyStart()));
//      startPeriod.set(Calendar.DATE, 1);
//      int year = Integer.valueOf(rundata.getParameters().get("start_year")).intValue();
//      startPeriod.set(year,startPeriod.get(Calendar.MONTH),1,0,0,0);
      setFileName(FILE_NAME);// + bookFormat.format(startPeriod.getTime()));
    } catch (Exception e){
      logger.error("Exception", e);
    }  
  }
  
  @Override
  public boolean write(RunData rundata, Context context, HSSFWorkbook wb){

    if (wb == null) return true;
    
    // 前期
    //IMXlsWriter firstTerm = new CashFlowFirstTermXlsWriter(rundata);
    // 後期
    //IMXlsWriter latterTerm = new CashFlowLatterTermXlsWriter(rundata);
    
    // 帳票データ書き込み
    boolean res = true;
      //firstTerm.write(rundata, context, wb) &&
      //latterTerm.write(rundata, context, wb);    
    return res;
  }
  
  protected String getCompanyStart()
  throws ALDBErrorException{
    try {
      DataContext dataContext = DatabaseOrmService.getInstance()
      .getDataContext();

      String sql =  " SELECT " +
                    "  IMW_M_HANYO.VALUE AS 会社設立日 " +
                    " FROM IMW_M_HANYO " +
                    " WHERE IMW_M_HANYO.PARENT_HANYO_ID = 10 ";
      
      if (sql==null || "".equals(sql)){
        return null;
      }
      SQLTemplate q = new SQLTemplate(ImwTExtTimecardDetail.class, sql, false);
      q.setFetchingDataRows(true);
      List list = dataContext.performQuery(q);
      DataRow obj = (DataRow)list.get(0);
      String companyStart = obj.get("会社設立日").toString();
      return companyStart;

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

  /** Add 20110304 KOHAMA Start Excelファイル名の文字化けに対応 */
  /**
   * HTTPレスポンスにエクセルファイルを出力します。
   * @param rundata
   * @param context
   * @param wb
   * @return true:成功 false:失敗
   */
  public boolean output(RunData rundata, Context context, HSSFWorkbook wb) {
    try {
      ServletOutputStream out = null;
      HttpServletResponse response = rundata.getResponse();

      String fileName_full = FILE_NAME + ".xls";
      byte[] sjis = fileName_full.getBytes("Shift_JIS");
      String fname = new String(sjis, "ISO8859_1");

      response.setHeader("Content-disposition", "attachment; filename=\""
          + fname + "\"");
      response.setContentType("application/msexcel");

      response.setHeader("Cache-Control", "private");
      response.setHeader("Pragma", "private");
      response.setHeader("Expires", "-1");

      // ファイル内容を直接ストリームへ出力
      out = response.getOutputStream();
      wb.write(out);

      out.flush();
      return true;
    } catch (Exception e) {
      logger.error("Exception", e);
      return false;
    }
  }
  /** Add 20110304 KOHAMA End */

}
