package cokr.xit.fims.cmmn.pdf;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.pdfbox.Loader;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageTree;
import org.springframework.util.ResourceUtils;

public class PDFUtil {

	public static List<Extraction> extract(String pdfName) {

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

        File file = null;
		try {
			file = ResourceUtils.getFile("classpath:sample/"+pdfName);
		} catch (FileNotFoundException e2) {
			e2.printStackTrace();
		}
        PDDocument pdDocument = null;
         try {
			pdDocument = Loader.loadPDF(file);
		} catch (IOException e) {
			e.printStackTrace();
		}


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

         int pageIndex = 0;

         Extraction extraction = new Extraction();

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

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

        	String epayNo = ExtractText.getExtractEpayNo(pdDocument, pageIndex+1);

            extraction.setEpayNo(epayNo);


            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) {
    			e1.printStackTrace();
    		}
            extraction.setBase64List(b64imageList);


            extractList.add(extraction);
         }

		return extractList;
	}


}
