/**
 * 
 */
package main;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.logging.ConsoleHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;

import main.manageclip.ManageKindleClip;
import main.managepdf.ManageAnotationToPDF;
import model.Anotation;
import util.CustomLogFormatter;

/**
 * Realiza merge de anotaes do Kindle em arquivos PDF extrados do mesmo.
 * 
 * @author Alex
 *
 */
public class MergeKindle {
	
	public static final String DEFUALT_MY_CLIPPINGS_TXT_NAME = "My Clippings.txt";
	private static final Logger L = Logger.getGlobal();

	/**
	 * @param args - argumentos vlidos so:
	 * 	<nome do pdf sem extensao>
	 */
	public static void main(String[] args) {
		Handler handler = new ConsoleHandler();
		handler.setFormatter(new CustomLogFormatter());
		L.addHandler(handler);
		L.setUseParentHandlers(false);
		L.setLevel(Level.INFO);
		L.log(Level.INFO, "Merge est abrindo arquivos e extraindo anotaes.");
		//TODO add extrao de argumentos
		
		ManageKindleClip manageKindleClip = new ManageKindleClip();
		ManageAnotationToPDF maToPDF = new ManageAnotationToPDF();
		String pdfNameFile = args[0];
		String pdfNameFileExt = pdfNameFile.concat(".pdf");
		
		try {
			File clipFile = new File("./"+DEFUALT_MY_CLIPPINGS_TXT_NAME);
			File pdfFile = new File("./"+pdfNameFileExt);
			
			List<Anotation> anotations = manageKindleClip.extractInfoFromClipFile(pdfNameFile, clipFile);
			if (anotations.size() == 0){
				Logger.getGlobal().log(Level.WARNING, "No foi encontrado nenhuma anotao para o PDF: "+pdfNameFile);
				return;
			}else
				Logger.getGlobal().log(Level.INFO, "Foi encontrado "+anotations.size()+" anotaes.");
			
			File createPDFWithInfo = maToPDF.createPDFWithInfo(anotations, pdfFile);
			if (createPDFWithInfo != null)
				L.log(Level.INFO, "Foi realizado o merge do PDF com sucesso.");
			else
				L.log(Level.INFO, "Algum erro ocorreu, o PDF no foi gerado.");
		} catch (FileNotFoundException e) {
			L.log(Level.SEVERE, "Erro ao tentar abrir arquivos: ", e);
		} catch (NoSuchElementException e) {
			L.log(Level.SEVERE, "Erro ao tentar extrair anotaes: ", e);
		} catch (IOException e) {
			L.log(Level.SEVERE, "Erro ao criar PDF com anotaes: ", e);
		}
	}

}

@@ -310,16 +310,80 @@
 .Logger;
+%0Aimport java.util.regex.Matcher;%0Aimport java.util.regex.Pattern;
 %0A%0Aimport
@@ -1349,16 +1349,143 @@
 rgs%5B0%5D;%0A
+%09%09Matcher matcher = Pattern.compile(%22(.*).pdf%22).matcher(pdfNameFile);%0A%09%09if (matcher.find())%0A%09%09%09pdfNameFile = matcher.group(1);%0A
 %09%09String

add tratamento de PDF com extensao passado como parametro.