/*
 * ====================================================================
 *
 * 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 javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletResponse;

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

import org.j69.eewiki.util.CacheConfig;
import org.j69.eewiki.util.SimpleCrypt;
import org.j69.eewiki.util.WebUtil;
import org.j69.eewiki.wiki.Wiki;

public class SavepageAction extends org.apache.struts.action.Action {

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

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

    public ActionForward execute(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {

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

        //ページIDパラメータの取得
        String pid = request.getParameter("pid");

        //コンテンツ格納
        Wiki wiki = new Wiki(WebUtil.getEncodeFileName(pid), request, msg);

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

        //フォームBeanの値取得
        //fromが無い場合はEditFormを作成
        HttpSession session = request.getSession();
        if (form == null) {
            form = new EditForm();
            if ("request".equals(mapping.getScope()))
                request.setAttribute(mapping.getAttribute(), form);
            else
                session.setAttribute(mapping.getAttribute(), form);
        }
        EditForm editform = (EditForm) form;
        String action = editform.getAction();
        String content = editform.getContent();
		String touchtime = editform.getTouchtime().trim();
		
		//他者によるファイルの更新をチェック、誰かが保存していたら保存は拒否する
		String LastTime = wiki.getLastModified();
		if (!LastTime.equals(touchtime)) {
			request.setAttribute("error_id" , msg.getMessage(request.getLocale(), "error.whotouch", ""));
			
			//表示するコンテンツのタイプを設定
			request.setAttribute("contentType", "content");

			request.setAttribute("content" , wiki);
			return mapping.findForward(FORWARD_View);
		}
		
        //プレビューの場合は、更新せず更新フォームにデータを返すだけ
        if (action.equals("preview")) {
            //フォームに値をセット
            editform.setContent(content);
            editform.setCmd("edit");
            editform.setNotimestamp(false);
            editform.setTouchtime(wiki.getLastModified());
            editform.setPassword("");
            editform.setPid(WebUtil.getEncodeFileName(pid));

            //コンテンツ格納（保存前なのでキャッシュに書き込む）
            wiki.setCachePage(content);

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

            request.setAttribute("content" , wiki);
            return mapping.findForward(FORWARD_View);
        }

        //パスワードのチェック
        if (wiki.isUsepasswd() == 1) {
        	String shadow = config_.getConfig("define.admin.passwd");
        	String cryppass = SimpleCrypt.genMD5String(editform.getPassword());
        	
            if (!shadow.equals(cryppass)) {
                request.setAttribute("contentType", "content");
                request.setAttribute("error_id" , msg.getMessage(request.getLocale(), "error.failpasswd", ""));

                //コンテンツ格納
                request.setAttribute("content" , wiki);
                return mapping.findForward(FORWARD_View);
            }
        }
    	
        //ページ更新
        wiki.setPageContent(editform.getContent(), !editform.getNotimestamp());

        //コンテンツ格納
        request.setAttribute("content" , wiki);

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

        //削除の場合はメッセージ表示
        if (content.equals(null) || content.equals(""))
            request.setAttribute("error_id" , msg.getMessage(request.getLocale(), "error.killpage", pid));

        return mapping.findForward(FORWARD_View);

    }

}