package kr.co.udapsoft.ebid.buyer.common.file;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.lowagie.text.Document;
import com.lowagie.text.Image;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.PdfImportedPage;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfWriter;

import kr.co.hsnc.common.base.WAFLogger;
import kr.co.hsnc.common.sql.WAFConnection;
import kr.co.hsnc.common.sql.WAFConnectionImpl;


public class PdfDownloadServlet extends HttpServlet {

	public PdfDownloadServlet() {

		super();
	}

    public void init(ServletConfig config) throws ServletException {

        super.init(config);
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	System.out.println("PdfDownloadServlet");
    	String szPROOF_DEPT = request.getParameter("PROOF_DEPT");        		
        String szPROOFDATE  = request.getParameter("PROOFDATE");
        String szPROOF_NO   = request.getParameter("PROOF_NO");
        String szPROOF_SEQ  = request.getParameter("PROOF_SEQ");
        String szPAGES_YN   = request.getParameter("PAGES_YN");
        String szJOB_GU     = request.getParameter("JOB_GU");
        if(szJOB_GU == null) szJOB_GU = "";
        if(szPAGES_YN == null) szPAGES_YN = "N";
        
      //선급전표일때 DOC020T의 조회를 위해 job_gu을 변경해준다.
        if(szJOB_GU.equals("20")){//외주선급
        	szJOB_GU = "('01','20')";
        }else if(szJOB_GU.equals("21")){//자재선급
        	szJOB_GU = "('02','21')";
        }else if(szJOB_GU.equals("23")){//조달선급
        	szJOB_GU = "('22','23')";
        }else if(szJOB_GU.equals("16")){//내륙, 해상 일경우 임시 추가  -2010.11.02 한지훈
        	szJOB_GU = "('02','16')";
        }
        
        ByteArrayInputStream inputStream = null;
        Document document = null;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        	
        try {

        	if( !szPROOF_DEPT.equals("") && !szPROOFDATE.equals("") && !szPROOF_NO.equals("") ) {
                
                if(szPAGES_YN.equals("N")) {
                	inputStream = SAC_PHOTO(szPROOF_DEPT, szPROOFDATE, szPROOF_NO, szPROOF_SEQ, szJOB_GU);
                	byte[] buffer = new byte[14096];              
                    BufferedInputStream  bis = new BufferedInputStream(inputStream);
                    BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());

                    int offset = 0;
                    try {             
                        while( (offset = bis.read(buffer)) != -1 ) {
                            bos.write(buffer, 0, offset);
                        }             
                        bos.flush();
                    }
                    catch (Exception e) {
                        WAFLogger.error(e.getMessage());
                    }
                    finally {
                        if( bos != null ) try { bos.close(); } catch(Exception e){}
                        if( bis != null ) try { bis.close(); } catch(Exception e){}
                    }
                    
                    response.setContentType("application/pdf");
                    response.setHeader("Content-Disposition", "inline;filename=\"hanwha.pdf\"");
                    
                    response.setContentLength(baos.size());
                    ServletOutputStream out = response.getOutputStream();
                    baos.writeTo(out);
                    out.flush();
                    
                	
                }
               	else {
            		// step1
            		document = new Document();
            		
        			// step2
        			//PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream());
            		PdfWriter writer = PdfWriter.getInstance(document, baos);
        			
        			// step3
            		//PdfWriter.getInstance(document, response.getOutputStream());
                    document.open();

               		SAC_PHOTO(document, writer, szPROOF_DEPT, szPROOFDATE, szPROOF_NO, szJOB_GU);
            		document.close();
            		
                    response.setContentType("application/pdf");
                    response.setHeader("Content-Disposition", "inline;filename=\"hanwha.pdf\"");
                    
                    response.setContentLength(baos.size());
                    ServletOutputStream out = response.getOutputStream();
                    baos.writeTo(out);
                    out.flush();
            		
               	}
            }           
            else {
                WAFLogger.error(this.getClass().getName() + " --> doGet() : 값이 없는 파라메터가 있습니다. ");
            }

        }catch(IOException ie) {
            WAFLogger.error(this.getClass().getName() + " --> doGet() : " + ie.getMessage());
            WAFLogger.error(ie);
        }catch(Exception ex) {
            WAFLogger.error(this.getClass().getName() + " --> doGet() : " + ex.getMessage());
            WAFLogger.error(ex);
        }
        
    }
    
private ByteArrayInputStream SAC_PHOTO(String szPROOF_DEPT,String szPROOFDATE,String szPROOF_NO,String szPROOF_SEQ,String szJOB_GU) throws Exception {
		
		WAFConnection conn = new WAFConnectionImpl();
       
        PreparedStatement pstmt = null;        
		StringBuffer sql = new StringBuffer();		
		ResultSet rs = null;
        try {
            
        	Connection connection = conn.getConnection();
						
			sql.append("   SELECT PHOTO					         \n");			
			sql.append("   FROM   DOC021T						 \n");
			sql.append("   WHERE  PROOF_DEPT  = '" + szPROOF_DEPT + "'   \n");			         
			sql.append("   AND  PROOFDATE  = TO_DATE('" + szPROOFDATE + "','YYYYMMDD')   \n");
			sql.append("   AND  PROOF_NO  = '" + szPROOF_NO + "'   \n");
			sql.append("   AND  PROOF_SEQ  = '" + szPROOF_SEQ + "'   \n");
			
			
			pstmt = connection.prepareStatement(sql.toString());
			
		
			
			rs = pstmt.executeQuery();					

            if( rs.next() ) {
                return IOUtil.toByteArrayInputStream(rs.getBinaryStream("PHOTO"));
            }
            return null;
        }
        catch(Exception e) {

            WAFLogger.error(this.getClass().getName() + " --> SAC_PHOTO() : " + e.getMessage());
            WAFLogger.error("SQL : " + sql.toString());
            WAFLogger.error(e);
            return null;
        }
        finally {
        	rs.close();
        	pstmt.close();
            conn.close();
        }
    }  	
	
	/*
	BLOB PDF를 묶어서 보여준다
	*/
	private void SAC_PHOTO(Document document, PdfWriter writer, String szPROOF_DEPT, String szPROOFDATE, String szPROOF_NO, String szJOB_GU) throws Exception {
		
		WAFConnection conn = new WAFConnectionImpl();
       
        PreparedStatement pstmt = null;        
		StringBuffer sql = new StringBuffer();		
		ResultSet rsPhoto = null;
		
		// step1
//		Document document = new Document();
		
        try {
        	
			// step2
//			PdfWriter writer = PdfWriter.getInstance(document,
//					new FileOutputStream("d:\\temp\\pdf\\test1.pdf"));
			
			// step3
//			document.open();
			document.setMargins(0, 0, 0, 0);
            
			// PDF 검색
        	Connection connection = conn.getConnection();
						
			sql.append("   SELECT a.PHOTO, a.proof_seq, a.proc_gu, a.proof_cd, a.proof_gu \n");
			sql.append("    FROM   DOC021T a	,doc020t b						 \n");
			sql.append("   WHERE  a.PROOF_DEPT  = '" + szPROOF_DEPT + "'   \n");			         
			sql.append("     AND  TO_CHAR(a.PROOFDATE, 'YYYYMMDD')  = '" + szPROOFDATE.replaceAll("-", "") + "'   \n");
			sql.append("     AND  a.PROOF_NO  = '" + szPROOF_NO + "'   \n");
			//sql.append("     AND  a.PROOF_SEQ  = '" + szPROOF_NO + "'   \n");
			if(!szJOB_GU.equals("")){
				sql.append("     and  b.job_gu in "+szJOB_GU+"   \n");
			}
			sql.append("     and  a.proof_dept(+) = b.proof_dept   \n");
			sql.append("     and  a.proofdate(+) = b.proofdate   \n");
			sql.append("     and  a.proof_no(+) = b.proof_no    \n");
			sql.append("     AND  a.photo IS NOT NULL AND LENGTH (a.photo) > 0		\n");
			sql.append("   AND  (instr(lower(a.FILE_NM),'.xml')  = 0  or  a.file_nm is null ) \n");
			sql.append("   ORDER BY PROOF_SEQ   \n");
			
        	// 테스트용 쿼리 : http://172.17.217.243/sac/SACManagementInputPictureDownServlet?PROOF_DEPT=x&PROOFDATE=x&PROOF_NO=x
//			sql.append("SELECT photo FROM doc021t WHERE photo is not null and length(photo) > 0 AND ROWNUM < 4");
			
			WAFLogger.debug("\n\t #################### "+ sql.toString());
			
			pstmt = connection.prepareStatement(sql.toString());
			rsPhoto = pstmt.executeQuery();
			int iCount = 0;

			// PDF 생성
			while (rsPhoto.next()) {
				InputStream inputAppend = rsPhoto.getBlob("photo")
						.getBinaryStream();
				PdfReader otherPDF = new PdfReader(inputAppend);

WAFLogger.debug("\n\t #################### getNumberOfPages = "+ otherPDF.getNumberOfPages());
				
				for (int iPage = 1; iPage <= otherPDF.getNumberOfPages(); iPage++) {
					PdfImportedPage page = writer.getImportedPage(otherPDF, iPage);
					Image image = Image.getInstance(page);
					
WAFLogger.debug("\n\t #################### getWidth = ["+ image.getWidth() +"] getHeight = ["+ image.getHeight() +"]");

					// 노무비 지급명세서, 외주기성고계산서는 가로로 회전
					if( rsPhoto.getString("proc_gu").equals("30") && (rsPhoto.getString("proof_gu").equals("12")) || rsPhoto.getString("proof_gu").equals("21")) {
WAFLogger.debug("\n\t #################### 가로회전 ["+ rsPhoto.getString("proof_gu") +"]");
						image.setRotation(-(float)Math.PI / 2);
						document.setPageSize(new Rectangle(image.getHeight(), image.getWidth()));
					} else {
						document.setPageSize(new Rectangle(image.getWidth(), image.getHeight()));
					}

					document.newPage();
					
					document.add(image);
				}
				
				if( otherPDF.getNumberOfPages() > 0)
					iCount++;
			}
			
			// 증빙이 없을때
			if( iCount <= 0 ) {
				//document.newPage();
				document.add(new Paragraph("Data not found!"));
			}
			
			// step 5
//			document.close();
        }
        catch(Exception e) {

            WAFLogger.error(this.getClass().getName() + " --> SAC_PHOTO() : " + e.getMessage());
            WAFLogger.error("SQL : " + sql.toString());
            WAFLogger.error(e);
        }
        finally {
        	rsPhoto.close();
        	pstmt.close();
            conn.close();
            
//            return document;
        }
    }  	
	
}
