package kr.co.udapsoft.common.util;

import java.awt.Dimension;
import java.awt.Insets;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.StringReader;
import java.net.MalformedURLException;
import java.security.InvalidParameterException;

import kr.co.hsnc.common.base.WAFLogger;
import kr.co.hsnc.common.config.WAFConfig;
import kr.co.hsnc.common.util.ValueObject;

import org.zefer.pd4ml.PD4Constants;
import org.zefer.pd4ml.PD4ML;
import org.zefer.pd4ml.PD4PageMark;

import crosscert.Hash;

public class PDFMaker {
	
	private int htmlWidth = 750;
	private String header = null;
	private String footer = null;
	private String footerDefault = "*본 계약서는 상기업체 간에 전자서명법  등 관련법령에 근거하여 전자서명으로 체결한 전자계약서입니다.<br>&nbsp;&nbsp;전자계약 진위여부는 협력업체포털시스템(http://partner.sgcenc.co.kr)에서 확인하실 수 있습니다.";
	private String cont_no = "";
	private String cont_chasu = "";
	private String file_seq = "";
	private String random_no = "";
	private String cont_userno = ""; // 사용자 계약번호


	public static void main(String[] args) throws InvalidParameterException, MalformedURLException, IOException{
		PDFMaker ed = new PDFMaker();
		//ed.generatePDF("file:///d:/CJ-GLS 택배대리점 계약서.html", new File("d:/CJ-GLS 택배대리점 계약서.pdf"), PD4Constants.A4);
		
		try {
			File f = new File("D:/Project4/pd4ml/html/", "엔지니어링 표준하도급계약서(전문).html");
			FileReader reader = new FileReader(f);
			BufferedReader buffer = new BufferedReader(reader);
			
			String html = "";
			String str = buffer.readLine();
			
			while(str!=null) {
				html += str;
				str =  buffer.readLine();
			}
			buffer.close();
			
			

			StringBuffer documentContents = new StringBuffer();
			//documentContents.append("<html><body>");

			documentContents.append("<html><head><style type=\"text/css\">");
			documentContents.append("<!--");
			documentContents.append("		td {  font-family: \"나눔고딕\",\"Arial\"; font-size: 12px; font-style: normal; letter-spacing:0; color: black;line-height:150%}");
			documentContents.append("		.lineTable { border-collapse:collapse; border:1 solid black }");
			documentContents.append("		.lineTable td { border:1 solid black }");
			documentContents.append("		.lineTable .noborder { border:0 }");	
			documentContents.append("-->");
			documentContents.append("</style>");
			documentContents.append("</head><body>");
			documentContents.append(html);
			documentContents.append("</body></html>");
			
			ed.generatePDF(documentContents.toString(), "D:/Project4/pd4ml/html/", "엔지니어링 표준하도급계약서(전문).pdf"); 
		}
		catch(IOException e) {
			e.printStackTrace();			
		}
	}
	
	public String getContNo() {
		return cont_no+"-"+cont_chasu+"-"+random_no;
	}

	public void setContNo(String cont_no, String cont_chasu, String random_no, String file_seq) {
		this.cont_no = cont_no;
		this.cont_chasu = cont_chasu;
		this.random_no = random_no;
		this.file_seq = file_seq;
	}

	private String getUserContNo() {
		return this.cont_userno;
	}
	public void setUserNo(String cont_userno) {
		this.cont_userno = cont_userno;
	}
	
	public String getHeader() {
		return header;
	}

	public void setHeader(String header) {
		this.header = header;
	}

	public String getFooter() {
		return footer;
	}

	public void setFooter(String footer) {
		this.footer = footer;
	}
	
	public int getHtmlWidth() {
		return htmlWidth;
	}

	public void setHtmlWidth(int htmlWidth) {
		this.htmlWidth = htmlWidth;
	}
	
	/**
	 * PDF 문서 생성
	 * @param url
	 * @param outputPDFFile
	 * @param format
	 * @return
	 */
	public boolean generatePDF(String url, File outputPDFFile, Dimension format) {
		FileOutputStream fos = null;
		

		try{
			fos = new FileOutputStream(outputPDFFile);
			PD4ML pd4ml = new PD4ML();
			
			PD4PageMark headerMark = new PD4PageMark();
			headerMark.setAreaHeight( 30 );				//header 영역 설정
			
			//header 데이터 셋팅
			if(header == null){
				if(!this.getUserContNo().equals(""))
					headerMark.setHtmlTemplate("<table border=0 width=100%><tr><td align=\"right\" valign=\"top\" ><font size=1 color=\"#5B5B5B\">* 계약번호: "+this.getUserContNo()+"</font></td></tr></table>");
				else
					headerMark.setHtmlTemplate("");
			}else{
				headerMark.setHtmlTemplate(header);
			}
			pd4ml.setPageHeader(headerMark);
			
			//footer 영역설정
			PD4PageMark footerMark = new PD4PageMark();
			footerMark.setAreaHeight( 40 );
			
			//footer 데이터 셋팅
			if(footer == null){
				footerMark.setHtmlTemplate("<table width='100%' height='35' border='0'><tr><td valign='bottom'><font size=1 color=\"#5B5B5B\">"+footerDefault+ " (관리번호:"+this.getContNo()+")</font></td></tr></table>");
			}else{
				footerMark.setHtmlTemplate("<span><font size=1 color=\"#5B5B5B\">"+ getFooter() +"</font></span>");
			}
			pd4ml.setPageFooter(footerMark);
			
			pd4ml.setPageInsets(new Insets(10,20,5,20));						//여백설정
			pd4ml.setHtmlWidth(getHtmlWidth());									//변환할 html의 width 정보
			pd4ml.setPageSize(PD4Constants.A4);									//용지모양 A4설정
			//pd4ml.setPageSize(pd4ml.changePageOrientation(PD4Constants.A4));	//가로로 설정
			pd4ml.useTTF("java:fonts", true);									//지정한 폰트 사용
			//pd4ml.setDefaultTTFs("Nanum Gothic", "Times New Roman", "Arial");	//default 폰트 설정
			pd4ml.setDefaultTTFs("Nanum Gothic", "Times New Roman", "Arial");	//default 폰트 설정
			pd4ml.enableDebugInfo();
			pd4ml.render(new java.net.URL(url), fos);
			return true;
		}catch(Exception e){
			e.printStackTrace();
			return false;
		}finally{
			if(fos != null)
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
	}
	
	
	public ValueObject makeContPdf(ValueObject vo){
		ValueObject pdf = null;
		
		try{
			String fontSize = "12px";
			if(!vo.get("font_size").equals("")){
				fontSize = vo.get("font_size");
			}
			
			String pdfDir = WAFConfig.get("waf.repository.path")+"/cont/";
			String fileDir = vo.get("folder") +"/"+ vo.get("cont_no")+"/";
			String fileName = vo.get("cont_no")+"_"+vo.get("cont_chasu")+"_"+vo.get("file_seq")+".pdf";
			String path = pdfDir + fileDir+fileName;
			
			StringBuffer documentContents = new StringBuffer();
			//documentContents.append("<html><body>");
	
			documentContents.append("<html><head><style type=\"text/css\">");
			documentContents.append("<!--");
			documentContents.append("		td {  font-family: \"굴림체\",\"Arial\"; font-size: "+fontSize+"; font-style: normal; letter-spacing:0; color: black;line-height:150%}");
			documentContents.append("		.lineTable { border-collapse:collapse; border:1 solid black }");
			documentContents.append("		.lineTable td { border:1 solid black }");
			documentContents.append("		.lineTable .noborder { border:0 }");
			documentContents.append("		.nText td { text-align:justify; vertical-align:top;}");
			documentContents.append("-->");
			documentContents.append("</style>");
			documentContents.append("		<meta http-equiv='Content-Type' content='application/xhtml+xml; charset=utf-8' />");
			documentContents.append("</head><body>");
			documentContents.append(vo.get("html"));
			documentContents.append("</body></html>");
			WAFLogger.debug("시작~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
			WAFLogger.debug(documentContents.toString());
			WAFLogger.debug("끝~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
			//WAFLogger.debug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
			//WAFLogger.debug(documentContents);
			//WAFLogger.debug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
			this.setContNo(vo.get("cont_no"), vo.get("cont_chasu"), vo.get("true_random"),vo.get("file_seq"));
			this.setUserNo(vo.get("cont_userno"));
			this.setHtmlWidth(750);
			
			//하도급 대금 지급 서식 작성은 footer와 header를 셋팅한다.
			if (vo.get("true_random").isEmpty()){
				this.setFooter("본 문서는 상기업체 간에 전자서명법등 관련법령에 근거하여 전자서명으로 체결한 전자문서입니다.");
				this.setHeader(" ");
			}
			boolean result = this.generatePDF(documentContents.toString(), pdfDir+fileDir, fileName);
			if(!result){
				return null;
			}
			WAFLogger.debug("Exception PDFMAKER : ");
			
			pdf = new ValueObject();
			pdf.set("file_path", fileDir);
			pdf.set("file_name", fileName);
			pdf.set("file_size", new File(path).length());
			pdf.set("file_ext", "pdf");
			pdf.set("file_hash", getHash(pdfDir+fileDir+fileName));
			return pdf;
		}catch(Exception e){
			WAFLogger.error("Exception PDFMAKER : " + e.getMessage());
			return null;
		}
	}
	
	/**
	 * PDF 문서 생성
	 * @param html
	 * @param outputDir
	 * @param outputFileName
	 * @return
	 */
	public boolean generatePDF(String html, String outputDir, String outputFileName) {
		FileOutputStream fos = null;
		
		try{
			WAFLogger.debug(outputDir+outputFileName);
			File outputDirFile = new File(outputDir);
			if(outputDirFile.exists() == false) outputDirFile.mkdirs();
			fos = new FileOutputStream(new File(outputDir+outputFileName));
			
			PD4ML pd4ml = new PD4ML();

			
			PD4PageMark headerMark = new PD4PageMark();
			headerMark.setAreaHeight( 30 );				//header 영역 설정
			
			//header 데이터 셋팅
			if(header == null){
				if(!this.getUserContNo().equals(""))
					headerMark.setHtmlTemplate("<table border=0 width=100%><tr><td align=\"right\" valign=\"top\" ><font size=1 color=\"#5B5B5B\">* 계약번호: "+this.getUserContNo()+"</font></td></tr></table>");
				else
					headerMark.setHtmlTemplate("");
			}else{
				headerMark.setHtmlTemplate(header);
			}
			pd4ml.setPageHeader(headerMark);
			
			//footer 영역설정
			PD4PageMark footerMark = new PD4PageMark();
			footerMark.setAreaHeight( 40 );
			
			//footer 데이터 셋팅
			if(footer == null){
				footerMark.setHtmlTemplate("<table width='100%' height='35' border='0'><tr><td valign='bottom'><font size=1 color=\"#5B5B5B\">"+footerDefault+ " (관리번호:"+this.getContNo()+")</font></td></tr></table>");
			}else{
				footerMark.setHtmlTemplate("<span><font size=1 color=\"#5B5B5B\">"+ getFooter() +"</font></span>");
			}
			pd4ml.setPageFooter(footerMark);
			
			pd4ml.setPageInsets(new Insets(10,20,5,20));						//여백설정
			pd4ml.setHtmlWidth(getHtmlWidth());									//변환할 html의 width 정보
			pd4ml.setPageSize(PD4Constants.A4);									//용지모양 A4설정
			//pd4ml.setPageSize(pd4ml.changePageOrientation(PD4Constants.A4));	//가로로 설정
			pd4ml.useTTF("java:fonts", true);									//지정한 폰트 사용
			pd4ml.setDefaultTTFs("Nanum Gothic", "Times New Roman", "Arial");	//default 폰트 설정
			pd4ml.enableDebugInfo();
			
			pd4ml.render(new StringReader(html), fos);
			return true;
		}catch(Exception e){
			e.printStackTrace();
			WAFLogger.error("Exception PDF : " + e.getMessage());
			return false;
		}finally{
			if(fos != null)
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
	}
	
	
	/**
	 * Hash 정보 가져오기
	 * @param sOtherFullDir
	 * @return
	 * @throws ConfigurationException 
	 * @throws ConfigurationException 
	 * @throws IOException 
	 */
	public String	getHash(String	sOtherFullDir)
	{
		FileInputStream	fis		=	null;
		String 			sHash	=	"";
		try {
			/*
			String	sBaseDir	=	WAFConfig.get("waf.repository.path")+"/cont";
			
			if(sBaseDir.lastIndexOf("/") == sBaseDir.length() - 1)
			{
				sBaseDir	=	sBaseDir.substring(0,sBaseDir.length()-1);
			}
			
			if(sOtherFullDir.indexOf("/") == 0)
			{
				sOtherFullDir	=	sOtherFullDir.substring(1);
			}
			String	sFullFilePath	=	sBaseDir	+	"/"	+	sOtherFullDir;
			*/
			
			String	sFullFilePath = sOtherFullDir;
			//sFullFilePath	=	StrUtil.replace(sFullFilePath,"\\",File.separator);
			//sFullFilePath	=	StrUtil.replace(sFullFilePath,"/",File.separator);
			
			WAFLogger.debug("getHash : " + sFullFilePath);
			
			fis					=	new FileInputStream(new File(sFullFilePath));
			int		iFileLen	=	fis.available();
			byte[]	b			=	new	byte[iFileLen];
			int		iRet		=	fis.read(b);
			Hash	hash		=	new	Hash();
			
			iRet	=	hash.GetHash(b, b.length);
			if(iRet	==	0)
			{
				sHash	=	new	String(hash.contentbuf);
			}else
			{
				sHash	=	"";
			}
		} catch (FileNotFoundException e) {
			WAFLogger.error("[ERROR "+this.getClass().getName() + ".getHash()] :" + e.toString());
			//throw new FileNotFoundException("[ERROR "+this.getClass().getName()+".getHash()] " + e.toString());
		} catch (IOException e) {
			WAFLogger.error("[ERROR "+this.getClass().getName() + ".getHash()] :" + e.toString());
			//throw new IOException("[ERROR "+this.getClass().getName()+".getHash()] " + e.toString());
		} finally
		{
			try {
				if(fis != null) fis.close();
			} catch (IOException e) {
				WAFLogger.error("[ERROR "+this.getClass().getName() + ".getHash()] :" + e.toString());
				//throw new IOException("[ERROR "+this.getClass().getName()+".getHash()] " + e.toString());
			}
		}
		return	sHash;
	} 
}
