/*********************************************************************************************************
 * 프로그램명 : TagFilter.java 프로그램설명 : 프로젝트와 관련된 정보를 얻을수 있는 class 작성자 : 강원중 작성일 : 2002.01.06 변경일 : 2004.09.16
 **********************************************************************************************************/
package kr.co.kihyun.text.html;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.ByteBuffer;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.jdo.PersistenceManager;
import javax.jdo.Transaction;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import kr.co.kihyun.beans.entity.Board;
import kr.co.kihyun.beans.entity.TotDoc;
import kr.co.kihyun.beans.entity.TotReport;
import kr.co.kihyun.beans.entity.util.PMF;

import kr.co.kihyun.beans.user.HttpSSOLogin;
import kr.co.kihyun.db.CommonDBManager;
import kr.co.kihyun.io.FileUtil;
import kr.co.kihyun.io.IUploadable;
import kr.co.kihyun.lang.MLong;
import kr.co.kihyun.lang.MString;
import kr.co.kihyun.moumi.MoumiConfig;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sun.mail.iap.Response;
@WebServlet("/servlet/kr.co.kihyun.text.html.HttpViewer")
public class HttpViewer extends HttpServlet {

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;
	private static final Logger LOG = LoggerFactory.getLogger(HttpViewer.class);

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

	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {


			ServletContext sContext = getServletContext();
			ServletOutputStream out = res.getOutputStream();

            String fileName = URLDecoder.decode(MString.checkNull(req.getParameter("fileName")), "UTF-8");
            String checkFile = MString.checkNull(req.getParameter("checkFile"));


			Long docID 		= MLong.parseLong(req.getParameter("docID"));
			Long reportID 	= MLong.parseLong(req.getParameter("reportID"));
			String dtID 	= MString.checkNull(req.getParameter("deptID"));
			Long boardID 	= MLong.parseLong(req.getParameter("boardID"));

			String mode = MString.checkNull(req.getParameter("mode"));
			String conType = MString.isNull(sContext.getMimeType(fileName)) ? "application/octet-stream" : sContext.getMimeType(fileName);

			res.setContentType(conType + ";charset=utf-8");
			String attacheFileDir = MoumiConfig.getFileDirectory()+"/"+docID+"/"+reportID+"/"+dtID;

			//LJH
            String fname=URLEncoder.encode(fileName, "UTF-8").replaceAll(":","_").replace("+", " ") +";";
            String fnameE=URLEncoder.encode(fileName, "UTF-8").replaceAll(":","_").replace("+", " ") +";";
            String fnameD=URLDecoder.decode(fileName, "UTF-8").replaceAll(":","_").replace("+", " ") +";";

            //3.디렉토리 경로 조작(getParameter)_CWE-22/23/36 : Add by KWON,HAN
            fname = fnameD;
            LOG.debug("fname: {}", fname);
            if(fname.contains("..") || fname. contains("/")) { // 특수문자열 검증
                LOG.debug("HttpViewer doPost ===");
                LOG.debug("3.디렉토리 경로 조작(getParameter)_CWE-22/23/36 : Test OK {}", fname);
                LOG.debug("=====================");
                return;
            }
            fname = fnameE;
            if("Y".equals(checkFile) && fileName.indexOf(".xls") != -1 && fname.length() >= 110){
                res.setHeader("Content-Disposition","attachment; filename="+fname.substring(fname.length()-110, fname.length()));
            }else{
                res.setHeader("Content-Disposition","attachment; filename="+fname);
            }
            res.setHeader("Cache-Control","private");   // 바로 열기 안되던 부분 수정 테스트.

        	//보드일경우 파일에서 읽기
            if(boardID != null){
            	String fileurl=FileUtil.getBoardAttachFileUrl(boardID, fileName, req);
            	String rtpath=req.getSession().getServletContext().getRealPath(fileurl)+"/";

				File file = new File(rtpath);
				if(file.exists()){
					FileInputStream fis = null;
					try{
						fis = new FileInputStream(rtpath+fileName);

						int b=fis.read();
						while(b!=-1){
							out.write(b);
							b=fis.read();
						}
						fis.close();
					System.out.println("fileurl ====  " + fileurl);
					System.out.println("rtpath ====  " + rtpath);
					System.out.println("file ====  " + file);

					}catch(Exception e){
						e.printStackTrace();
						out.flush();
						out.close();
					}finally{
						fis.close();
						File[] files = file.listFiles();
						System.out.println("fiels === "+ files);
						for(int i=0; i< files.length; i++){
							files[i].delete();
						}
						file.delete();
					}

				}



            }else{		//Report,doc

            	PersistenceManager pm = PMF.get().getPersistenceManager();
				Transaction tx = pm.currentTransaction();
				try {
					tx.begin();

					if ("csv".equals(mode)) {
						ServletUtil.returnFile(new File(MoumiConfig.getRoot(), "user.csv"), out);
					} else {
						IUploadable uploadable = null;
						if (reportID != null) {

    	    				File fnFile = new File(attacheFileDir+"/"+fileName);
    	    				if(fnFile.exists()){  //시스템에 리포트 파일이 존재하면
    	    					FileInputStream fis = null;
						        try {
									fis = new FileInputStream(fnFile);
						            byte[] content = new byte[(int) fnFile.length()];
						            fis.read(content);	//파일의 내용을 읽는다.
						            out.write(content);	//읽은 파일내용을 압축파일에 쓴다.
						            fis.close();
						        } catch (IOException e) {
						           	e.printStackTrace();
						    		out.flush();
						    		out.close();
						        } finally {
						        	fis.close(); //파일실행을 끊어줌.// 예외 발생 여부와 상관없이 자원 해제
						        }
    	    				}else{ //시스템에서 리포트 파일이 존재하지 않으면 DB에서 가져오기
    							uploadable = pm.getObjectById(TotReport.class, reportID);
    	    				}

						} else if (docID != null) {
							uploadable = pm.getObjectById(TotDoc.class, docID);
						}

						if(null != uploadable){
							if (uploadable.getAttachments() == null || uploadable.getAttachments().get(fileName) == null) {
								throw new FileNotFoundException("File '" + fileName + "' does not exist.");
							}

							Byte[] content = uploadable.getAttachments().get(fileName).toArray(new Byte[]{});
		                    byte[] contentPri = null;

		                    if (content.length > 0) {
		                        contentPri = new byte[content.length];

		                        for (int i = 0; i < content.length; i++) {
		                        	contentPri[i] = content[i].byteValue();
		                        }
		                    }

							out.write(contentPri);
							out.flush();
							out.close();
						}
					}

					tx.rollback();
				} catch (FileNotFoundException e) {
					LOG.error("{}. {} not found.", e.getMessage(), fileName);
					res.setContentType("text/html;charset=utf-8");
					out.println("<script> alert('File not found');window.close();</script>");
				} catch (IOException e) {
					res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Problem sending file: " + e.getMessage());
				} finally {
					if (tx.isActive()) {
						tx.rollback();
					}
					pm.close();
				}
			}
	}
}
