package mprj.doerj.caderno.util;

import com.liferay.portal.kernel.util.PortalUtil;
import com.liferay.portal.kernel.util.StringPool;



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

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.CacheControl;
import javax.portlet.ClientDataRequest;
import javax.portlet.PortletContext;
import javax.portlet.PortletPreferences;
import javax.portlet.PortletRequest;
import javax.portlet.PortletResponse;
import javax.portlet.PortletURL;
import javax.portlet.ResourceRequest;
import javax.portlet.ResourceResponse;
import javax.portlet.ResourceURL;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.JAXBException;

import org.docx4j.XmlUtils;
import org.docx4j.openpackaging.Base;
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;
import org.w3c.dom.DOMException;
import org.w3c.dom.Element;

public class GeraCaderno {
	
	
	public static void processaCaderno(ActionRequest actionRequest,ActionResponse actionResponse,JSONArray listaConteudos,String dataDivulgacao) throws Docx4JException, JAXBException, IOException, ParseException{
		
		
		
		PortletContext context = actionRequest.getPortletSession().getPortletContext();
		
		//String pathTemplate = context.getRealPath("");
		
		String pathTemplate = "F:/LiferayWorkspacewithDevStudioDXP/workspace/mprj-doerj-caderno/src/main/resources/META-INF/resources/template";
		String conteudo="";
		String orgao="";
		String titulo="";
		PortletPreferences prefs = actionRequest.getPreferences();
		  CadernoUtil util = new CadernoUtil();
		 MainDocumentPart currentDocumentPart = null;
		 WordprocessingMLPackage templatePackage = WordprocessingMLPackage.load(new File(pathTemplate + "/" + "TemplateCaderno.docx"));
		//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", StringPool.BLANK);
		    variables.put("PGJ", PGJ);
		    
		    
		    String CGMP = prefs.getValue("CGMPConfig", StringPool.BLANK);
		    variables.put("CGMP", CGMP);
		    
		    String SGJA = prefs.getValue("SGJAConfig", StringPool.BLANK);
		    variables.put("SGJA", SGJA);
		    
		    String SGJPI = prefs.getValue("SGJPIConfig", StringPool.BLANK);
		    variables.put("SGJPI", SGJPI);
		    
		    String SGJACI = prefs.getValue("SGJACIConfig", StringPool.BLANK);
		    variables.put("SGJACI", SGJACI);
		    
		    String SGJACDH = prefs.getValue("SGJACDHConfig", StringPool.BLANK);
		    variables.put("SGJACDH", SGJACDH);
		    
		    String SGJRIDP = prefs.getValue("SGJRIDPConfig", StringPool.BLANK);
		    variables.put("SGJRIDP", SGJRIDP);
		    
		    String CG = prefs.getValue("CGConfig", StringPool.BLANK);
		    variables.put("CG", CG);
		    
		    String CJ = prefs.getValue("CJConfig", StringPool.BLANK);
		    variables.put("CJ", CJ);

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

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

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

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

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

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

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

		    String ARIDP = prefs.getValue("ARIDPConfig", StringPool.BLANK);
		    variables.put("ARIDP", ARIDP);
		    
		    String AI = prefs.getValue("AIConfig", StringPool.BLANK);
		    variables.put("AI", AI);
		    
		    String AAP = prefs.getValue("AAPConfig", StringPool.BLANK);
		    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;
		File exportFile = new File(pathTemplate + "/" + nomeArquivo + ".docx");
		templatePackage.save(exportFile);
		
		PortletRequest pRequest = PortalUtil.getLiferayPortletRequest(actionRequest);
		PortletResponse pResponse = PortalUtil.getLiferayPortletResponse(actionResponse);

		HttpServletRequest req = PortalUtil.getHttpServletRequest(pRequest);
        HttpServletResponse res = PortalUtil.getHttpServletResponse(pResponse);
        res.setHeader("Content-Disposition", "attachment; filename="+nomeArquivo + ".docx");//
        res.setHeader("Content-Transfer-Encoding", "binary");
        res.setContentType("application/force-download");
        
        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);
                  }
              
        res.flushBuffer();
		
	}

}
