/**
 * ********************************************************************************
 * 프로그램명 : HttpFileList.java 작 성 자 : wonseok Lee 작 성 일 : 2017. 8.10 최신변경일 :
 * 설명:  접수자료 > 자료입력 화면에 첨부파일을 보여준다.
 * 1.0
 **********************************************************************************
 */
package kr.co.kihyun.beans.totsys.board;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.net.URLEncoder;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Map;
import java.util.List;
import java.util.Set;
import java.sql.SQLException;

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 kr.co.kihyun.beans.user.HttpSSOLogin;
import kr.co.kihyun.lang.MString;
import kr.co.kihyun.moumi.MoumiConfig;
import kr.co.kihyun.db.CommonDBManager;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ibm.icu.util.StringTokenizer;
@WebServlet("/servlet/kr.co.kihyun.beans.totsys.board.HttpFileList")
public class HttpFileList extends HttpServlet {

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


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

        res.setContentType("text/html;charset=UTF-8");

        String usID = HttpSSOLogin.getLoginID(req);
        String reportID = "";
        String docID = "";
        String dtID = "";
        int accumulateFileSize = 0;     // 업로드된 파일들의 총 누적 크기(byte)를 저장할 변수.
        String svrFilenames = "";
        String usrFilenames = "";
        String fileSizes = "";
        long sumFileSize = 0;
        int fileCount = 0;
        String fileInfos = "";
        String connURL = "";
        String attacheFileDir = "";

        docID = MString.checkNull(req.getParameter("docID"));
       	reportID = MString.checkNull(req.getParameter("reportID"));
       	dtID = MString.checkNull(req.getParameter("dtID"));

       	//1. 페이지 로딩시 ATTACHMENTS 컬럼에 파일이 있고 해당 첨부파일 경로에 파일이 존재하지 않으면 DB에서 읽은 파일을 실제 경로에 입력한다.
       	//2. attachements_path 컬럼도 update한다.
       	StringBuilder sql1 = new StringBuilder(250);
    	String attachementsPath = "";
		String fileCheck = "";

       	attacheFileDir = MoumiConfig.getFileDirectory()+"/"+docID+"/"+reportID+"/"+dtID;
       	String files_nm = "";

    	CommonDBManager acdbm1=new CommonDBManager();
    	ResultSet rs1 = null;


        //3. JSP 파일에 보여줄 파일정보를 전달한다.(SELECT BOX에 파일 표시를 위해)
        try{
//			rs1= acdbm1.execQuery(" SELECT FILE_CHECK FROM MOUMI_TOT_REPORT WHERE id= ?",reportID);
//
//			if(rs1.next()){
//				fileCheck = rs1.getString(1);
//			}
//			rs1.close();
//			acdbm1.pstmt.close();
//
//			if("N".equals(fileCheck)) {
//				LOG.debug("fileCheck>>>>>>>>>>["+fileCheck+"]");
//				rs1= acdbm1.execQuery("SELECT ATTACHMENTS FROM MOUMI_TOT_REPORT WHERE id= ?",reportID);
//
//				InputStream is = null;
//				ObjectInputStream ois = null;
//
//				try{
//					if(rs1.next()){
//						is=rs1.getBinaryStream(1);
//						if(is!=null){
//							ois=new ObjectInputStream(is);
//							ArrayList<String> rslt=new ArrayList<String>();
//		    				Map<String, List<Byte>> map= (Map<String, List<Byte>>)ois.readObject();
//		    	    		Set<String> filenames=map.keySet();
//		    		    	File attacheDir=new File(attacheFileDir);
//		    	    		if(!attacheDir.exists()) attacheDir.mkdirs();
//
//							//첨부파일 경로에 동일한 이름의 파일이 있는지 비교한다.
//		    	    		for (String fn : filenames) {
//		    	    			rslt.add(fn);
//		    	    			try {
//		    	    				File fnFile=new File(attacheDir+"/"+fn);
//		    	    				attachementsPath += fnFile.getPath()+";";
//		    	    				files_nm += fnFile.getName() + ";";
//		    	    				if(!fnFile.exists()) {
//			    	    				List<Byte> flist=map.get(fn);
//			    	    				if(flist==null)continue;
//			    	    				FileOutputStream fos=new FileOutputStream(fnFile);
//			    	        			for(int b:flist)fos.write(b);
//			    	        			fos.flush();
//			    	        			fos.close();
//		    	    				}
//		    	    			} catch (Exception e) {
//		    	    				e.printStackTrace();
//		    	    			}
//		    				}
//						} //end if
//					}
//					rs1.close();
//					acdbm1.pstmt.close();
//
//    	    		sql1.delete(0,sql1.length());
//    	            sql1.append("UPDATE MOUMI_TOT_REPORT SET ATTACHMENTS_PATH = ?, FILE_CHECK = 'Y' WHERE ID = ?");
//    	            acdbm1.execUpdate(sql1.toString(), files_nm, reportID);
//    	            acdbm1.pstmt.close();
//
//    	            sql1.delete(0,sql1.length());
//    	            sql1.append("UPDATE MOUMI_TOT_REPORT_VERSION SET ATTACHMENTS_PATH = ? WHERE REPORT_ID = ? AND ID=(SELECT MAX(ID) FROM MOUMI_TOT_REPORT_VERSION WHERE DEL_TYPE = 'N' AND REPORT_ID = ?)");
//    	            acdbm1.execUpdate(sql1.toString(),files_nm, reportID, reportID);
//    	            acdbm1.pstmt.close();
//
//    	    		acdbm1.commit();
//
//
//				}catch(IOException e){
//					e.printStackTrace();
//				}catch(Exception e){
//					e.printStackTrace();
//				}finally{
//					if(ois != null) ois.close();
//					if(is != null) is.close();
//				}
//			}


			//DB에서 첨부파일 목록을 읽어온다.
//    		sql1.delete(0,sql1.length());
    		//blob 칼럼 사이즈 구하는 중요 쿼리(5008)
            sql1.append("SELECT ATTACHMENTS_PATH AS FILES_NM, LENGTH(ATTACHMENTS_PATH) - LENGTH(REPLACE(ATTACHMENTS_PATH,';','')) AS FILES_CNT, LENGTH(ATTACHMENTS)/5008*1000 AS FILES_SIZE FROM MOUMI_TOT_REPORT WHERE ID = ? ");
            rs1 = acdbm1.execQuery(sql1.toString(), reportID);

            if(rs1.next()){
            	svrFilenames 	= (null == rs1.getObject("FILES_NM")) ? "" : rs1.getString("FILES_NM");
                usrFilenames 	= svrFilenames;
                fileInfos 		= fileInfos +"add;";
                fileCount 		= rs1.getInt("FILES_CNT");
                sumFileSize 	= rs1.getLong("FILES_SIZE");
            }
            rs1.close();
            acdbm1.pstmt.close();

            svrFilenames = URLEncoder.encode(svrFilenames, "UTF-8");
            usrFilenames = URLEncoder.encode(usrFilenames, "UTF-8");


	    } catch (Exception ex) {
	        acdbm1.rollback();
	        ex.printStackTrace();
	    } finally {
	    	try{
	    		if(null != rs1) rs1.close();
	    	}catch(Exception e1){
	    		e1.printStackTrace();
	    	}
		    acdbm1.execClose();


		    if (reportID != null) {

	            String allowURL[] = { "/totsys/common/inc/board/doc/write_file_list.jsp" };
	            connURL = allowURL[0] + "?attacheFileRead=true";
	            connURL = connURL + "&svrFilenames="+svrFilenames;
	            connURL = connURL + "&usrFilenames="+usrFilenames;
	            connURL = connURL + "&fileCount="+fileCount;
	            connURL = connURL + "&fileSize="+fileSizes;
	            connURL = connURL + "&sumFileSize="+sumFileSize;
	            connURL = connURL + "&fileInfos="+fileInfos;
	            connURL = connURL + "&reportID="+reportID;
	            connURL = connURL + "&docID="+docID;
	            connURL = connURL + "&dtID="+dtID;
	            LOG.debug("URL 주소로 자동 접속 연결11111 : HttpFileList.doPost() connURL={} : Test OK", connURL);
	        }
	        res.sendRedirect(connURL);
	    }
    }
}
