package cokr.xit.fims.cmmn.pdf.extraction;

import java.awt.geom.Rectangle2D;
import java.io.IOException;
import java.util.regex.Pattern;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.pdfbox.text.PDFTextStripperByArea;

public class ExtractText {

	public static final String REGEXP_PATTERN_NUMBER = "^[\\d]*$";

	public static String getExtractByStng(PDDocument document, int pageNum,
			float x, float y, float w, float h) {

		try {
			PDFTextStripperByArea textStripper = new PDFTextStripperByArea();

			Rectangle2D rect = new java.awt.geom.Rectangle2D.Float(x, y, w, h);
			textStripper.addRegion("region", rect);

	        PDPage docPage = document.getPage(pageNum-1);

	        textStripper.extractRegions(docPage);

	        String textForRegion = textStripper.getTextForRegion("region");

	        System.out.println("영역지정으로 추출된 텍스트");
	        System.out.println(textForRegion);

	        return textForRegion;

		} catch (IOException e) {

			throw new RuntimeException("자료추출 오류."+e);
		}

	}


	public static String getExtractEpayNo(PDDocument pdDocument, int pageNum) {
		String epayNo = "";

		PDFTextStripper Tstripper = new PDFTextStripper();

		Tstripper.setStartPage(pageNum);
        Tstripper.setEndPage(pageNum);
        String summaryText = null;

        try {
			summaryText = Tstripper.getText(pdDocument);
		} catch (IOException e) {
			throw new RuntimeException("자료추출 오류."+e);
		}

        String[] textArr = summaryText.split("\r?\n|\r");

        for(int i=0; i < textArr.length; i++) {
        	boolean isNumber = Pattern.matches(REGEXP_PATTERN_NUMBER, textArr[i]);
        	if(isNumber) {
        		if(textArr[i].length() == 19) {
        			epayNo = textArr[i];
        		}
        	}
        }
		return epayNo;
	}

}
