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

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.pdfbox.Loader;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageTree;

import cokr.xit.fims.cmmn.CmmnUtil;
import cokr.xit.foundation.data.DataObject;

public class PDFExtractionUtil {
	public static List<Extraction> extract(String pdfPath, List<DataObject> extractStngs) {

		List<Extraction> extractList = new ArrayList<Extraction>();

        File file = null;
		try {
			file = new File(pdfPath);
		} catch (Exception e2) {
			throw new RuntimeException("자료추출 오류."+e2);
		}
        PDDocument pdDocument = null;
         try {
			pdDocument = Loader.loadPDF(file);
		} catch (IOException e) {
			throw new RuntimeException("자료추출 오류."+e);
		}


         PDPageTree pages = pdDocument.getPages();
         int pageCount = pages.getCount();

         int pageIndex = 0;

         Extraction extraction = new Extraction();

         for(;pageIndex < pageCount; pageIndex++) {

        	Map<String,String> textItem = new HashMap<String,String>();

        	extraction = new Extraction();
        	extraction.setPage(pageIndex+1);

        	for(DataObject extractStng : extractStngs) {

        		float x = CmmnUtil.mmToPt(extractStng.number("LEFT_PSTN").floatValue());
        		float y = CmmnUtil.mmToPt(extractStng.number("TOP_PSTN").floatValue());
        		float w = CmmnUtil.mmToPt(extractStng.number("WIDTH_SZ").floatValue());
        		float h = CmmnUtil.mmToPt(extractStng.number("HEIGHT_SZ").floatValue());

        		String text0 = ExtractText.getExtractByStng(pdDocument, pageIndex+1, x, y, w, h);
            	textItem.put(extractStng.string("EXTR_ARTCL_NM"), text0);
        	}

        	extraction.setTextItem(textItem);


            PDPage page = pages.get(pageIndex);
            List<String> b64imageList = new ArrayList<>();
            try {
            	ExtractImageEngine printer = new ExtractImageEngine();
    			printer.processPage(page);
    			b64imageList = printer.getBase64List();
    			printer.clearBase64List();

            } catch (IOException e1) {
            	throw new RuntimeException("자료추출 오류."+e1);
    		}
            extraction.setBase64List(b64imageList);


            extractList.add(extraction);
         }

		return extractList;
	}
}
