package mprj.doerj.caderno.util;

import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.theme.ThemeDisplay;
import com.liferay.portal.kernel.util.ContentTypes;
import com.liferay.portal.kernel.util.PortalUtil;
import com.liferay.portal.kernel.util.WebKeys;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.ParseException;
import java.util.HashMap;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletContext;
import javax.portlet.PortletPreferences;
import javax.portlet.PortletResponse;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;

import org.docx4j.openpackaging.exceptions.Docx4JException;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.WordprocessingML.HeaderPart;
import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart;
import org.json.JSONArray;
import org.json.JSONObject;

public class GeraCaderno {
	
	
	public void processaCaderno(ActionRequest actionRequest,ActionResponse actionResponse,JSONArray listaConteudos,String dataDivulgacao) throws Docx4JException, JAXBException, IOException, ParseException, PortalException{
		
		
		
		PortletContext context = actionRequest.getPortletSession().getPortletContext();
		
		//String pathTemplate = context.getRealPath("");
		
		//InputStream templateCaderno = GeraCaderno.class.getClass().getResourceAsStream("/META-INF/resources/template/TemplateCaderno.docx");
		InputStream templateCaderno = getClass().getResourceAsStream("/META-INF/resources/template/TemplateCaderno.docx");
		ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY);
		//String templateCaderno = PortalUtil.getPortalURL(themeDisplay) + "/o/mprj.doerj.caderno/template/TemplateCaderno.docx";
		
		String conteudo="";
		String orgao="";
		String titulo="";
		PortletPreferences prefs = actionRequest.getPreferences();
		  CadernoUtil util = new CadernoUtil();
		 MainDocumentPart currentDocumentPart = null;
		 
		 System.out.println("Iniciando teste do JAXBContext...");
		 JAXBContext.newInstance("org.docx4j.openpackaging.contenttype");
		 System.out.println("Finalizado teste do JAXBContext.");
		 
		 //WordprocessingMLPackage templatePackage = WordprocessingMLPackage.load(new File(templateCaderno.toString()));
		 //WordprocessingMLPackage templatePackage = WordprocessingMLPackage.load(new File(templateCaderno));
		 WordprocessingMLPackage templatePackage = WordprocessingMLPackage.load(templateCaderno);
		
		 //System.out.println(XmlUtils.marshaltoString(templatePackage.getMainDocumentPart().getJaxbElement(), true, true));
		 WordprocessingMLPackage acumuladoPackage = WordprocessingMLPackage.createPackage();

//Preenche os dados do cabeçalho
		 
		 MainDocumentPart headerDocumentPart = templatePackage.getMainDocumentPart();
		 
		 
		 MainDocumentPart mainPart = templatePackage.getMainDocumentPart();
		 HeaderPart headerPart = templatePackage.getHeaderFooterPolicy().getDefaultHeader();
		 HeaderPart firstPageHeaderPart = templatePackage.getHeaderFooterPolicy().getFirstHeader();
		 	
		   // VariablePrepare.prepare(templatePackage);
		    
		    JSONObject cabecalho = new JSONObject(listaConteudos.getJSONObject(0).toString());
		    
		    String edicao = "EDIÇÃO TESTE";
		    String disponibilizacao = util.gerarDataCabecalho(dataDivulgacao);
		    String publicacao = "PUBLICAÇÃO TESTE";
	
		    
		    
//Cria o hash map com as variáveis para substuição dos dados dos cabeçalhos e expediente		    
		   HashMap<String, String> variables = new HashMap<String, String>();
		    variables.put("edicao", edicao);
		    variables.put("disponibilizacao", disponibilizacao);
		    variables.put("publicacao", publicacao);
		    
		    String PGJ = prefs.getValue("PGJConfig", "");
		    variables.put("PGJ", PGJ);
		    
		    
		    String CGMP = prefs.getValue("CGMPConfig", "");
		    variables.put("CGMP", CGMP);
		    
		    String SGJA = prefs.getValue("SGJAConfig", "");
		    variables.put("SGJA", SGJA);
		    
		    String SGJPI = prefs.getValue("SGJPIConfig", "");
		    variables.put("SGJPI", SGJPI);
		    
		    String SGJACI = prefs.getValue("SGJACIConfig", "");
		    variables.put("SGJACI", SGJACI);
		    
		    String SGJACDH = prefs.getValue("SGJACDHConfig", "");
		    variables.put("SGJACDH", SGJACDH);
		    
		    String SGJRIDP = prefs.getValue("SGJRIDPConfig", "");
		    variables.put("SGJRIDP", SGJRIDP);
		    
		    String CG = prefs.getValue("CGConfig", "");
		    variables.put("CG", CG);
		    
		    String CJ = prefs.getValue("CJConfig", "");
		    variables.put("CJ", CJ);

		    String AE = prefs.getValue("AEConfig", "");
		    variables.put("AE", AE);

		    String CMPROCJ = prefs.getValue("CMPROCJConfig", "");
		    variables.put("CMPROCJ", CMPROCJ);
		    
		    String CMPROMJ = prefs.getValue("CMPROMJConfig", "");
		    variables.put("CMPROMJ", CMPROMJ);
		    
		    String CSI = prefs.getValue("CSIConfig", "");
		    variables.put("CSI", CSI);
		    
		    String CEAF = prefs.getValue("CEAFConfig", "");
		    variables.put("CEAF", CEAF);

		    String OUVI = prefs.getValue("OUVIConfig", "");
		    variables.put("OUVI", OUVI);
		    
		    String SGMP = prefs.getValue("SGMPConfig", "");
		    variables.put("SGMP", SGMP);

		    String AAOMC = prefs.getValue("AAOMCConfig", "");
		    variables.put("AAOMC", AAOMC);
		    
		    String ARCC = prefs.getValue("ARCCConfig", "");
		    variables.put("ARCC", ARCC);

		    String GAOMC = prefs.getValue("GAOMCConfig", "");
		    variables.put("GAOMC", GAOMC);
		    
		    String ARCCRI = prefs.getValue("ARCCRIConfig", "");
		    variables.put("ARCCRI", ARCCRI);

		    String AC = prefs.getValue("ACConfig", "");
		    variables.put("AC", AC);

		    String ADHM = prefs.getValue("ADHMConfig", "");
		    variables.put("ADHM", ADHM);

		    String ARIDP = prefs.getValue("ARIDPConfig", "");
		    variables.put("ARIDP", ARIDP);
		    
		    String AI = prefs.getValue("AIConfig", "");
		    variables.put("AI", AI);
		    
		    String AAP = prefs.getValue("AAPConfig", "");
		    variables.put("AAP", AAP);

		    
		    firstPageHeaderPart.variableReplace(variables);
		    headerPart.variableReplace(variables);
		    mainPart.variableReplace(variables);
		 
		 
	      //AINDA FALTA IMPLEMENTAR A CLASSE Estilos estilo = new Estilos();
	      //AINDA FALTA IMPLEMENTAR A CLASSE estilo.alterStyleSheet(acumuladoPackage);
	       WordprocessingMLPackage firstPagePackage = WordprocessingMLPackage.createPackage();
	     
	       boolean firstPage=true;
	  
	 //faz a leitura da listagem de todos os conteúdos recebidos pelo serviço Rest      
		for(int i=0;i<listaConteudos.length();i++){
			
			WordprocessingMLPackage wordCurrentPackage = WordprocessingMLPackage.createPackage();
		           JSONObject obj = new JSONObject(listaConteudos.get(i).toString());
		           
		           
		           orgao = obj.get("ORGAO").toString();
		            orgao = util.tratarString(orgao,"titulo");
					
		           
		            titulo = obj.get("NOME").toString();
					titulo = util.tratarString(titulo,"titulo");
					
					
					conteudo = obj.get("CONTEUDO").toString();
			
					conteudo=util.tratarString(conteudo,"conteudo");
			
				//AINDA N�O FOI IMPLEMENTADO	wordCurrentPackage = util.ConverterHTML(conteudo,orgao,titulo,actionRequest);

					currentDocumentPart = wordCurrentPackage.getMainDocumentPart();
					acumuladoPackage.getMainDocumentPart().getContent().addAll(currentDocumentPart.getContent());
					wordCurrentPackage = null;
					currentDocumentPart =null;
			       
		}
	
		MainDocumentPart acumuladoDocumentPart = acumuladoPackage.getMainDocumentPart();
	
		//AINDA FALTA IMPLEMANTAR A CLASSE estilo.alterStyleSheet(templatePackage);

		templatePackage.getMainDocumentPart().getContent().addAll(acumuladoDocumentPart.getContent());
		
		util.ORGAO="";
		util.TITULO="";
		//File exportFile = new File("C:/Users/diogo.souza/Documents/Caderno DO/testeDoc4JNovo.docx");
		String dataNomeArquivo = dataDivulgacao.replace("/", "-");
		String nomeArquivo="caderno_doerj_" + dataNomeArquivo + ".docx";
		
//		InputStream nomeArquivoInputStream = getClass().getResourceAsStream("/META-INF/resources/template/"+nomeArquivo);
//		File exportFile = new File(nomeArquivoInputStream.toString());
		
		//cria o arquivo temporário que será utilizado na resposta da requisição
		File exportFile = File.createTempFile("caderno_doerj_tmp_", ".docx");
		
		try {
			templatePackage.save(exportFile);
			
			PortletResponse pResponse = PortalUtil.getLiferayPortletResponse(actionResponse);
	
	        HttpServletResponse res = PortalUtil.getHttpServletResponse(pResponse);
	        res.setHeader("Content-Disposition", "attachment; filename=" + nomeArquivo);//
	        res.setContentType(ContentTypes.APPLICATION_MSWORD);
	        
	        try (FileInputStream in = new FileInputStream(exportFile);) {
		        OutputStream out = res.getOutputStream();
		       
		        byte[] buffer = new byte[4096];
  
		        int numBytesRead;
		        
		        while ((numBytesRead = in.read(buffer)) > 0) {
		        	out.write(buffer, 0, numBytesRead);
		        }
		        
		        out.flush();
		        res.flushBuffer();
	        }
	        
		}
		finally {
			exportFile.delete();
		}
		
	}

}
