/*
 * Aipo is a groupware program developed by Aimluck,Inc.
 * Copyright (C) 2004-2008 Aimluck,Inc.
 * http://aipostyle.com/
 *
 * 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.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;

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

import org.apache.jetspeed.services.logging.JetspeedLogFactoryService;
import org.apache.jetspeed.services.logging.JetspeedLogger;
import org.apache.jetspeed.services.resources.JetspeedResources;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.turbine.util.RunData;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.context.Context;

import com.aimluck.eip.common.ALDBErrorException;
import com.aimluck.eip.common.ALEipUser;
import com.aimluck.eip.common.ALPageNotFoundException;
import com.aimluck.eip.common.ALPermissionException;
import com.aimluck.eip.exttimecard.ExtTimecardResultDataNew;
import com.aimluck.eip.exttimecard.ExtTimecardSelectData;
import com.aimluck.eip.exttimecard.ExtTimecardExcelAllSelectData;
import com.aimluck.eip.exttimecard.ExtTimecardExcelAllCreate;
import com.aimluck.eip.exttimecard.util.ExtTimecardUtils;
import com.aimluck.eip.orm.DatabaseOrmService;
import com.aimluck.eip.services.accessctl.ALAccessControlConstants;
import com.aimluck.eip.util.ALEipUtils;

/**
 * タイムカードのファイル出力を取り扱うクラスです
 */
public class ExtTimecardXlsExportAllScreen extends ExtTimecardXlsExportScreen {
  /** logger */
  private static final JetspeedLogger logger = JetspeedLogFactoryService
      .getLogger(ExtTimecardXlsExportScreen.class.getName());

  public static final String FILE_NAME = "timecard.xls";

  /** ログインユーザーID */
  private String userid;

  /** ログインユーザー名 */
  private String username;

  /** ユーザーリスト */
  private List userslist;

  /** 一時フォルダへのフォルダ */
  private File rootFolder;

  private String view_month;

  /** アクセス権限の機能名 */
  private String aclPortletFeature = null;
  
  /** 負荷プロファイル */
  private final String FILEPATH_PROPERTIES = JetspeedResources.getString(
      "aipo.conf", "")
      + "/MaothReport.properties";
  
  /** 記事を読むの設定ファイル */
  
  private String getDailyBatchDocumentProperty(String key) {
    try {
      Properties prop = new Properties();

      // ファイルが存在しない場合はnullを返す。
      File file = new File(FILEPATH_PROPERTIES);
      if (!file.exists()) {
        return null;
      }

      prop.load(new FileInputStream(FILEPATH_PROPERTIES));
      String value = prop.getProperty(key);

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

  /**
   * 初期化処理を行います。
   * 
   * @param action
   * @param rundata
   * @param context
   */
  public void init(RunData rundata, Context context)
      throws ALPageNotFoundException, ALDBErrorException {

    String target_user_id = rundata.getParameters().getString(
        ExtTimecardUtils.TARGET_USER_ID);
    userid = Integer.toString(ALEipUtils.getUserId(rundata));

    rootFolder = ExtTimecardUtils.getRootFolder(DatabaseOrmService
        .getInstance().getOrgId(rundata), ALEipUtils.getUserId(rundata));

    view_month = rundata.getParameters().getString("view_month");
    
    userslist = ALEipUtils.getUsers("LoginUser");

    // アクセス権
    if (target_user_id == null || "".equals(target_user_id)
        || userid.equals(target_user_id)) {
      aclPortletFeature = ALAccessControlConstants.POERTLET_FEATURE_TIMECARD_TIMECARD_SELF;
    } else {
      aclPortletFeature = ALAccessControlConstants.POERTLET_FEATURE_TIMECARD_TIMECARD_OTHER;
    }

    super.init(rundata, context);
  }

  protected boolean createXLSFile(RunData rundata, Context context,
      String filepath) {
    try {

      String templateFilepath = rundata.getServletContext().getRealPath(
          "/ExcelTemplate");
      String tempfile = getDailyBatchDocumentProperty("templatePath");
      FileInputStream excelFile = new FileInputStream(templateFilepath + "/"
          + tempfile);
      POIFSFileSystem fs = new POIFSFileSystem(excelFile);
      // 負荷がテンプレート
      HSSFWorkbook wb = new HSSFWorkbook(fs);
      createHSSFWorkbook(rundata, context, wb);
      File file = new File(filepath);
      if (file.exists()) {
        file.delete();
      }

      FileOutputStream output = new FileOutputStream(file);
      
      wb.write(output);
      output.flush();
      output.close();
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }
    return true;
  }
  
  protected boolean createHSSFWorkbook(RunData rundata, Context context,
      HSSFWorkbook wb) {
    try {
      setupTimecardSheet(rundata, context, wb);
    } catch (Exception e) {
      logger.error("TimecardCsvExportScreen", e);
      return false;
    }
    return true;
  }

  private void setupTimecardSheet(RunData rundata, Context context,
      HSSFWorkbook wb) throws Exception {

    ExtTimecardSelectData listData = new ExtTimecardSelectData();
    listData.initField();
    listData.setRowsNum(1000);
    listData.doViewList(this, rundata, context);
    
    ExtTimecardResultDataNew rdn = listData.getTimecardResultData();
    ExtTimecardExcelAllCreate.execute(rdn, wb);

  }

  protected String getFolderPath() {
    return rootFolder.getAbsolutePath();
  }

  protected String getFileName() {
    return FILE_NAME;
  }

  /**
   * アクセス権限チェック用メソッド。<br />
   * アクセス権限の機能名を返します。
   *
   * @return
   */
  public String getAclPortletFeature() {
    return aclPortletFeature;
  }
  
  /**
   * ダウンロードをやめて、作成ファイルを直接ストリーム出力するようにしたもの
   * 
   */
  protected void doOutput(RunData rundata) throws Exception {
    VelocityContext context = new VelocityContext();
    ServletOutputStream out = null;

    try {
      init(rundata, context);

      doCheckAclPermission(rundata, context, getDefineAclType());

      String templateFilepath = rundata.getServletContext().getRealPath("/ExcelTemplate");
      String tempfile = getDailyBatchDocumentProperty("templatePath");
      FileInputStream excelFile = new FileInputStream(templateFilepath + "/"
            + tempfile);
      POIFSFileSystem fs = new POIFSFileSystem(excelFile);
      HSSFWorkbook wb = new HSSFWorkbook(fs);
      
      for(int i = 1;i < userslist.size();i++){
        wb.cloneSheet(0);
     }

      ExtTimecardExcelAllSelectData listData = new ExtTimecardExcelAllSelectData();

      for(int i = 0;i < userslist.size();i++){
        ALEipUser user = (ALEipUser)userslist.get(i);
        listData.initField();
        listData.setTargetUserId(user.getUserId().toString());
        listData.setRowsNum(1000);
        listData.doViewList(this, rundata, context);
        
        listData.setJobInfo();
        ExtTimecardExcelAllCreate.executeVmLike(rundata, context, listData, wb,i);
      }
      HttpServletResponse response = rundata.getResponse();
      String fileName_full = String.format("%1$TY年%1$tm月 ", listData.getViewMonth().getValue()) + "勤務実績.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();
      
    } catch (ALPermissionException e) {
      ALEipUtils.redirectPermissionError(rundata);
    } catch (Exception e) {
      logger.error("[ERROR]", e);
    }
  }
  
  /**
   * ユーザーリスト内の指定IDユーザーの名前を取得します。
   * 
   * TODO:TimecardUtilへ移動
   * 
   * @param ls
   * @param id
   * @return
   */
  private static String getUserNameByList(List<ALEipUser> ls, String id){
    for(Iterator<ALEipUser> itr = ls.iterator(); itr.hasNext();){
      ALEipUser u = itr.next();
      if(u.getUserId().getValueAsString().equals(id))
        return u.getName().getValue();
    }

    return "";
  }
  
}
