/*
 * ====================================================================
 *
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 1999-2002 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution, if
 *    any, must include the following acknowlegement:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowlegement may appear in the software itself,
 *    if and wherever such third-party acknowlegements normally appear.
 *
 * 4. The names "The Jakarta Project", "Struts", and "Apache Software
 *    Foundation" must not be used to endorse or promote products derived
 *    from this software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache"
 *    nor may "Apache" appear in their names without prior written
 *    permission of the Apache Group.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 *
 */

package org.j69.eewiki.action;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;
import org.apache.struts.util.MessageResources;

import org.j69.eewiki.util.CacheConfig;
import org.j69.eewiki.wiki.Wiki;
import org.j69.eewiki.wiki.WikiConstants;

/**
 * CheckinFileAction.java created by EasyStruts - XsltGen.
 * http://easystruts.sf.net
 * created on 06-07-2003
 *
 * XDoclet definition:
 * @struts:action path="/CheckinFile" name="UploadForm" input="/form/.jsp" validate="true"
 * @struts:action-forward name="/pages/Viewpage.vm" path="/pages/Viewpage.vm"
 */
public class CheckinFileAction extends Action {

    //------------------------------------------------------------ Local Forwards
    static final private String FORWARD_View = "View";

    // コンフィグ
    private final static CacheConfig config_ = CacheConfig.getInstance( );

    /**
     * Method execute
     * @param ActionMapping mapping
     * @param ActionForm form
     * @param HttpServletRequest request
     * @param HttpServletResponse response
     * @return ActionForward
     * @throws Exception
     */
    public ActionForward execute(
        ActionMapping mapping,
        ActionForm form,
        HttpServletRequest request,
        HttpServletResponse response)
        throws Exception {

        String echo = "";
        boolean isUpload = true;

		//メッセージリソース
		MessageResources msg = getResources(request);

        UploadForm theForm = (UploadForm) form;

        //フォームからファイルオブジェクトを取得
        FormFile file = theForm.getUploadFile();

        //ファイル名
        String fileName= theForm.getFileName();
		//String fileName= new String(file.getFileName().getBytes(), "UTF-8");
        
        //拡張子
        String suffix = getSuffix(fileName);

        //コンテンツタイプの取得
        //String contentType = file.getContentType();

        if (!isUploadSuffix(suffix)) {
            echo = msg.getMessage(request.getLocale(), "error.filetype", suffix);
            //echo = suffix + "は、添付ファイルとして許可されていないファイルタイプです。";
            isUpload=false;
        }

        if (isUpload) {
            //アップロード上限サイズのチェック
            if (file.getFileSize() > config_.getConfigAsInt("define.upload.maxsize")) {
                echo = msg.getMessage(request.getLocale(), "error.maxsize", Integer.toString(file.getFileSize()), Integer.toString(config_.getConfigAsInt("define.upload.maxsize")));
                //echo = "ファイルサイズ：" + file.getFileSize()  + "Kは、ファイルサイズの上限 " + config_.getConfigAsInt("define.upload.maxsize") + "Kを超してます。";
                isUpload=false;
            }
        }

        //ページIDパラメータの取得　ここのページIDはフォームから直接なのでエンコードされている
        String pid = request.getParameter("pid");

        //Wiki作成
        Wiki wiki = new Wiki(pid, request, msg);

        if (isUpload) {
            //出力用にUploadディレクトリ名をコンフィグより取得し、物理ファイル名に変換
            String outputFilePath = config_.getConfig("define.wiki.basedir") + config_.getConfig("define.dir.upload");
            fileName = wiki.getEncodeFileName(fileName) + "." + suffix;
            outputFilePath = outputFilePath + "/" + fileName;

            //ファイル作成
            try {
				InputStream stream = file.getInputStream();
            	//テキスト扱いの場合
            	if (file.getContentType().equals("text/plain")) {
					OutputStream bos = new FileOutputStream(outputFilePath);
					BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
							                           new FileOutputStream(new File(outputFilePath)), WikiConstants.DEFAULT_FILE_ENCODING));

					BufferedReader br = new BufferedReader(new InputStreamReader(
					                                  stream, WikiConstants.DEFAULT_FILE_ENCODING));

					StringBuffer buffer = new StringBuffer();
					String str = null;
					while ((str = br.readLine()) != null) {
						buffer.append(str + "\n");
					}
					bw.write(buffer.toString());
					br.close();
					bw.close();
            	}
				//バイナリ扱いの場合
            	else {
					OutputStream bos = new FileOutputStream(outputFilePath);
					int bytesRead = 0;
					byte[] buffer = new byte[8192];
					while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
						bos.write(buffer, 0, bytesRead);
					}
					bos.close();
            	}
				stream.close();
            }
            catch (FileNotFoundException fnfe) {
                return null;
            }
            catch (IOException ioe) {
                return null;
            }
        }

        //Viewpageに遷移元を伝える
        request.setAttribute("from_id", "Uploadpage");

        //エラーの場合の遷移
        if (!echo.equals("")) {
            //表示するコンテンツのタイプを設定
            request.setAttribute("contentType", "upload");
            request.setAttribute("content" , wiki);

            request.setAttribute("error_id" , echo);
            return mapping.findForward(FORWARD_View);
        }

        //表示するコンテンツのタイプとコンテンツを設定
        request.setAttribute("contentType", "content");
        request.setAttribute("content" , wiki);

        return mapping.findForward(FORWARD_View);

    }

    /**
     * 拡張子の取得
     * @param filename 対象ファイル
     * @return 拡張子
     */
    private String getSuffix(String filename) {
        return filename.substring(filename.lastIndexOf(".") + 1);
    }

    /**
     * 添付可能な拡張子かどうか？
     * @param pageName 判定対象の拡張子
     * @return true:OK、false:NG
     **/
    private boolean isUploadSuffix(String suffix) {
        //使用可能な拡張子をコンフィグから配列で取得
        String[] fixedSuffix = config_.getConfigArray ("define.upload.suffix");

        for (int i = 0; i < fixedSuffix.length; i++) {
            if(fixedSuffix[i].equals(suffix)) return true;
        }
        return false;
    }
}
