/*
 * Aipo is a groupware program developed by Aimluck,Inc.
 * http://aipostyle.com/
 *
 * Copyright(C) 2012 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 javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

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.common.ALEipConstants;
import com.aimluck.eip.fileupload.FileuploadFormData;
import com.aimluck.eip.fileupload.beans.FileuploadBean;

/**
 * スケジュールポートレット添付ファイルアップロード処理を行うクラス
 * 
 */
public class ScheduleFileuploadJSONScreen extends ALJSONScreen {
  private static final JetspeedLogger logger =
    JetspeedLogFactoryService.getLogger(ScheduleFileuploadJSONScreen.class
      .getName());

  @Override
  protected String getJSONString(RunData rundata, Context context)
      throws Exception {
    String result = new JSONArray().toString();
    try {

      HttpServletResponse response = rundata.getResponse();
      response.setContentType("text/html; "
        + ALEipConstants.DEF_CONTENT_ENCODING);
      FileuploadFormData formData = new FileuploadFormData();
      formData.initField();
      if (formData.doUpdate(this, rundata, context)) {
        FileuploadBean filebean = formData.getNewAttachmentFile();
        // フォルダ名
        String folderName = filebean.getFolderName();
        // 添付ファイルID
        int fileId = filebean.getFileId();
        // 添付ファイル名
        String fileName = filebean.getFileNameEscape();
        // フォルダ名+添付ファイルIDを「：」区切り（ファイル名に使用できない文字）で渡す
        // クライアント側(javascript)で文字列を分解して処理
        result = folderName + ":" + fileId + ":" + fileName + ":" + "Complete";
      } else {
        JSONArray json =
          JSONArray.fromObject(context.get(ALEipConstants.ERROR_MESSAGE_LIST));
        result = json.toString();
      }
    } catch (Exception e) {
      logger.error("スケジュールポートレット：ファイルアップロード中に例外が発生しました" + e);
      JSONArray json = JSONArray.fromObject("ファイルアップロードに失敗しました。");
      result = json.toString();
    }
    return result;
  }
}
