/*********************************************************************************************************
 * 프로그램명 : HttpBoardDelete.java 프로그램설명 : 프로젝트와 관련된 정보를 얻을수 있는 class 작성자 : 강원중 작성일 : 2003.11.30 변경일 : 2003.12.13
 **********************************************************************************************************/

package kr.co.kihyun.beans.totsys.board;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

import javax.jdo.PersistenceManager;
import javax.jdo.Transaction;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import kr.co.kihyun.beans.entity.Board;
import kr.co.kihyun.beans.entity.Category;
import kr.co.kihyun.beans.entity.util.*;
import kr.co.kihyun.beans.user.HttpSSOLogin;
import kr.co.kihyun.io.FileUtil;
import kr.co.kihyun.lang.MLong;
import kr.co.kihyun.lang.MString;
import kr.co.kihyun.moumi.MoumiConfig;
import kr.co.kihyun.text.html.ServletUtil;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@WebServlet("/servlet/kr.co.kihyun.beans.totsys.board.HttpBoardDelete")
public class HttpBoardDelete extends HttpServlet {
        private static final Logger LOG = LoggerFactory.getLogger(HttpBoardDelete.class);
	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		doPost(req, res);
	}

	public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		res.setContentType("text/html");
		res.setContentType("text/html;charset=UTF-8");
		PrintWriter out = res.getWriter();
		HttpSession session = req.getSession(true);

		/*********** User HttpLogin check ***********/
		if (!HttpSSOLogin.isLogin(req)) {
			String connURL = "parent.parent.location='/totsys/login/login.jsp';";
			out.println(ServletUtil.getJavaScript(connURL));
			return;
		}

		/********** parameter value **********/
		Long boardID = MLong.parseLong(req.getParameter("boardID"), null);
                String callbackFunc = req.getParameter("callbackFunc");
		String usID = HttpSSOLogin.getLoginID(req);
		String returnURL = "history.go(-1)";

		PersistenceManager pm = new MPersistenceManager(PMF.get().getPersistenceManager());
		Transaction tx = pm.currentTransaction();
		try {
			tx.begin();
			kr.co.kihyun.beans.entity.Board mBoard = pm.getObjectById(kr.co.kihyun.beans.entity.Board.class, boardID);
			if (!mBoard.getUser(pm).getId().equals(usID) && HttpSSOLogin.getSysAuth(req) != MoumiConfig.SYSADM) {
				out.println(ServletUtil.alert(MoumiConfig.getMessageBundle().getString("moumi.message.popup.commonWay")));
				returnURL = "document.location.replace('/totsys/sysadm/board/board_list.jsp?boardGroupID="
						+ mBoard.getCategory().getId() + "')";
			} else {
				if (mBoard.getCategory().equals(Category.ID_TOT_DOC_COMMENT))
					out.println(ServletUtil.getJavaScript("window.close();"));
				ArrayList<Long> ids=new ArrayList<Long>();
				ids.add(boardID);
				if (mBoard.getChildBoards() != null){
					for (Board bd : mBoard.getChildBoards()) {
						ids.add(bd.getId());
					}
					pm.deletePersistentAll(mBoard.getChildBoards());
				}

				pm.deletePersistent(mBoard);
				returnURL = (String) session.getAttribute("delTargetURI");
				for (Long bid : ids) {
					try {
						FileUtils.deleteDirectory(new File(FileUtil.getGlobalBoardAttachmentsPath()+bid));
					} catch (Exception e) {
						// TODO: handle exception
					}
				}
			}
			tx.commit();
		} catch (Exception e) {
			out.println(ServletUtil.alert(MoumiConfig.getMessageBundle().getString("moumi.message.popup.deleteFail")));
			e.printStackTrace();
		} finally {
			if (tx.isActive())
				tx.rollback();
			pm.close();
                        if( MString.isNull(callbackFunc) ) {
                            out.println(ServletUtil.getJavaScript(returnURL));
                        }else{
                            //v2. 9.크로스사이트 스크립트 (PrintWrier) : Update by KWON,HAN
//                            out.println(ServletUtil.getJavaScript(callbackFunc));

                            // 수정 : 외부 입력값 필터링
                            String filtered_callbackFunc = callbackFunc.replaceAll("<","").replaceAll(">","").replaceAll("&","").replaceAll(",","");
                            LOG.debug("v2 9.크로스사이트 스크립트 (PrintWrier) : HttpBoardDelete.doPost() filtered_callbackFunc={}, Not Test", filtered_callbackFunc);
                            out.println(ServletUtil.getJavaScript(filtered_callbackFunc));
                            //============================================================
                        }
		}
	}
}
