package mprj.doerj.caderno.portlet;

import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.json.JSONFactoryUtil;
import com.liferay.portal.kernel.portlet.bridges.mvc.MVCPortlet;
import com.liferay.portal.kernel.search.ParseException;
import com.liferay.portal.kernel.servlet.SessionErrors;
import com.liferay.portal.kernel.servlet.SessionMessages;
import com.liferay.portal.kernel.theme.ThemeDisplay;
import com.liferay.portal.kernel.upload.UploadPortletRequest;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.kernel.util.PortalUtil;
import com.liferay.portal.kernel.util.WebKeys;

import java.io.IOException;
import java.io.PrintWriter;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.Portlet;
import javax.portlet.PortletException;
import javax.portlet.PortletURL;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;

import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.osgi.service.component.annotations.Component;

import mprj.doerj.caderno.constants.MprjDoerjCadernoPortletKeys;
import mprj.doerj.caderno.rest.RestServices;
import mprj.doerj.caderno.util.CadernoUtil;
import mprj.doerj.caderno.util.GeraCaderno;

/**
 * @author diogo.souza
 */
@Component(immediate = true, 
configurationPid = "mprj.doerj.caderno.configuration.DoerjCadernoPortletConfiguration",
property = { "com.liferay.portlet.display-category=category.sample",
		"com.liferay.portlet.instanceable=false", "com.liferay.portlet.scopeable=true",
		"com.liferay.portlet.header-portlet-css=/css/admin/admin.css",
		"com.liferay.portlet.header-portlet-css=/css/datepicker/bootstrap.min.css",
		"com.liferay.portlet.header-portlet-css=/css/datepicker/bootstrap-datepicker3.standalone.min.css",
		"com.liferay.portlet.header-portlet-css=/css/confirm/jquery-confirm.min.css",
		"com.liferay.portlet.header-portlet-javascript=/js/admin/jquery-1.10.2.min.js",
		"com.liferay.portlet.header-portlet-javascript=/js/datepicker/moment-with-locales.js",
		"com.liferay.portlet.header-portlet-javascript=/js/datepicker/transition.js",
		"com.liferay.portlet.header-portlet-javascript=/js/datepicker/collapse.js",
		"com.liferay.portlet.header-portlet-javascript=/js/datepicker/bootstrap.min.js",
		"com.liferay.portlet.header-portlet-javascript=/js/datepicker/bootstrap-datepicker.min.js",
		"com.liferay.portlet.header-portlet-javascript=/js/datepicker/bootstrap-datepicker.pt-BR.js",
		"com.liferay.portlet.header-portlet-javascript=/js/confirm/jquery-confirm.min.js",
		"com.liferay.portlet.header-portlet-javascript=/js/main.js",
		"com.liferay.portlet.header-portlet-javascript=/js/admin/admin.js", 
		"com.liferay.portlet.icon=/icon.png",
		"com.liferay.portlet.requires-namespaced-parameters=false", 
		"com.liferay.portlet.ajaxable=true",
		"com.liferay.portlet.control-panel-entry-category=MPRJ", 
		"com.liferay.portlet.control-panel-entry-weight=39",
		"com.liferay.portlet.preferences-unique-per-layout=false",
		"com.liferay.portlet.preferences-owned-by-group=true", 
		"com.liferay.portlet.add-default-resource=true",
		"com.liferay.portlet.css-class-wrapper=mprj-doerj-materia-web",
		"javax.portlet.display-name=Gestão de Matérias do Diário Oficial",
		"javax.portlet.expiration-cache=0",
		"javax.portlet.init-param.portlet-title-based-navigation=true", 
		"javax.portlet.init-param.template-path=/",

		"com.liferay.portlet.instanceable=true", 
		"javax.portlet.display-name=MprjDoerjCaderno",
		"javax.portlet.init-param.template-path=/", 
		"javax.portlet.init-param.view-template=/view.jsp",
		"javax.portlet.init-param.config-template=/configuration.jsp",
		"javax.portlet.name=" + MprjDoerjCadernoPortletKeys.MPRJDOERJCADERNO,
		"javax.portlet.resource-bundle=content.Language", 
		"javax.portlet.mime-type=text/html",
		"javax.portlet.security-role-ref=power-user,user" }, service = Portlet.class)
public class MprjDoerjCadernoPortlet extends MVCPortlet {

	final static Logger logger = Logger.getLogger(MprjDoerjCadernoPortlet.class);

	@Override
	public void render(RenderRequest renderRequest, RenderResponse renderResponse)
			throws IOException, PortletException {

		// ThemeDisplay themeDisplay = (ThemeDisplay)
		// resourceRequest.getAttribute(WebKeys.THEME_DISPLAY);
		// UploadPortletRequest
		// uploadRequest=PortalUtil.getUploadPortletRequest(resourceRequest);
		// String valor = ParamUtil.getString(resourceRequest, "parameter");
		String cmd = ParamUtil.getString(renderRequest, "caderno");
		// String dataDivulgacao = ParamUtil.getString(uploadRequest, "dataP");
		// String situacao = ParamUtil.getString(uploadRequest, "situacao");

		com.liferay.portal.kernel.json.JSONObject jsonResponse = JSONFactoryUtil.createJSONObject();

		if (cmd.equals("geraCaderno")) {

			try {
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		} else {
			try {
				jsonResponse.put("result", CadernoUtil.getDatasCadastradas());

			} catch (SystemException e) {
				// TODO Auto-generated catch block
				logger.error("Erro requisicao AJAX", e);
			} catch (java.text.ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			// Writing the result in resourceResponse writer.
			PrintWriter writer = renderResponse.getWriter();
			writer.println(jsonResponse);
			// Creating a JSON object which will contain the sum.
		}

		PortletURL renderUrl = renderResponse.createRenderURL();
		renderResponse.addProperty("Location", renderResponse.createRenderURL().toString());
		super.render(renderRequest, renderResponse);

		// super.doView(renderRequest, renderResponse);
	}
	
	public void geraCaderno(ActionRequest actionRequest, ActionResponse actionResponse)throws Exception {

		UploadPortletRequest uploadRequest=PortalUtil.getUploadPortletRequest(actionRequest);
		ThemeDisplay themeDisplay = (ThemeDisplay) uploadRequest.getAttribute(WebKeys.THEME_DISPLAY);
		String dataDivulgacao = ParamUtil.getString(uploadRequest, "dataP");
		String idStatus = ParamUtil.getString(uploadRequest, "situacao");
		
		
		JSONArray listaConteudos = new JSONArray();
		RestServices rest = new RestServices();
		String dataDivulgacaoRest = dataDivulgacao.replace("/", "");
		listaConteudos = rest.getRest(dataDivulgacaoRest,idStatus,actionRequest);
		SessionMessages.add(actionRequest, PortalUtil.getPortletId(actionRequest) + SessionMessages.KEY_SUFFIX_HIDE_DEFAULT_SUCCESS_MESSAGE);
	
		
		if(!mensagensDeErro(listaConteudos, dataDivulgacao, actionRequest)){
		GeraCaderno caderno = new GeraCaderno();
		
		caderno.processaCaderno(actionRequest, actionResponse,listaConteudos,dataDivulgacao);
		}else{
		
			String portletName = (String) actionRequest.getAttribute(WebKeys.PORTLET_ID);
			
		}
		
	}
	
	
	
	protected Boolean mensagensDeErro(JSONArray listaConteudos, String dataDivulgacao, ActionRequest actionRequest) throws ParseException{
		Boolean contemErro = Boolean.FALSE;
		
		if(listaConteudos.length()==0 && !dataDivulgacao.equals("")) {
			contemErro = Boolean.TRUE;
			actionRequest.setAttribute("erroListagemNula", true);
			
			SessionErrors.add(actionRequest, "erroListagemNula");
			SessionMessages.add(actionRequest, PortalUtil.getPortletId(actionRequest) + SessionMessages.KEY_SUFFIX_HIDE_DEFAULT_ERROR_MESSAGE);
		} else 	if(dataDivulgacao.equals("")) {
			contemErro = Boolean.TRUE;
			actionRequest.setAttribute("erroDataNula", true);
			SessionErrors.add(actionRequest, "erroDataNula");
			SessionMessages.add(actionRequest, PortalUtil.getPortletId(actionRequest) + SessionMessages.KEY_SUFFIX_HIDE_DEFAULT_ERROR_MESSAGE);
		} 
		return contemErro;
	}

}