package com.yeejoin.equipmanage.common.utils;

import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.SimpleBookmark;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

public class PdfUtil {
	
	private static Integer index = 1;

	public static MyNode getPdfNavs(String pdfUrl) {
		MyNode root = new MyNode();
		try {
			PdfReader reader = new PdfReader(pdfUrl);
			List<HashMap<String, Object>> list = SimpleBookmark.getBookmark(reader);
			if(list!=null && list.size()>0) {
				index = 1;
				root.setId(String.valueOf(index));
				for (Iterator<HashMap<String, Object>> i = list.iterator(); i.hasNext();) {
					showBookmark(i.next(), root);
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return root;
	}

	// 获取标题
	public static void showBookmark(HashMap<String, Object> bookmark, MyNode parentNode) {
		List<MyNode> children = parentNode.getChildren();
		MyNode n = new MyNode();
		n.setId(String.valueOf(index++));
		n.setPageInfo("page=" + getPageNumbers(bookmark));
		n.setText((String) bookmark.get("Title"));
		children.add(n);
//		System.out.println (bookmark.get ( "Title" )) ;  
//		System.out.println(getPageNumbers( bookmark));
		@SuppressWarnings("unchecked")
		ArrayList<HashMap<String, Object>> kids = (ArrayList<HashMap<String, Object>>) bookmark.get("Kids");
		if (kids == null){
			return;}
		for (Iterator<HashMap<String, Object>> i = kids.iterator(); i.hasNext();) {
			showBookmark(i.next(), n);
		}
	}

	// 获取页码
	public static Integer getPageNumbers(HashMap<String, Object> bookmark) {
		if (bookmark == null){
			return null;}

		if ("GoTo".equals(bookmark.get("Action"))) {

			String page = (String) bookmark.get("Page");
			if (page != null) {
				page = page.trim();
				int idx = page.indexOf(' ');
				int pageNum;
				if (idx < 0) {
					pageNum = Integer.parseInt(page);
				} else {
					pageNum = Integer.parseInt(page.substring(0, idx));
				}
				return pageNum;
			}

		}
		return null;
	}

}