package br.mp.mprj.portal.portlet.gestaomensagens.action;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletConfig;
import javax.portlet.PortletPreferences;
import javax.portlet.PortletRequest;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.portlet.ValidatorException;
import javax.servlet.ServletContext;

import br.mp.mprj.portal.portlet.gestaomensagens.service.model.GrupoDestinatario;
import br.mp.mprj.portal.portlet.gestaomensagens.service.model.GrupoDestinatarioClp;
import br.mp.mprj.portal.portlet.gestaomensagens.service.service.GrupoDestinatarioLocalServiceUtil;

import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.portlet.ConfigurationAction;
import com.liferay.portal.kernel.portlet.PortletConfigurationLayoutUtil;
import com.liferay.portal.kernel.servlet.SessionErrors;
import com.liferay.portal.kernel.servlet.SessionMessages;
import com.liferay.portal.kernel.util.Constants;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.kernel.util.PrefsParamUtil;
import com.liferay.portal.kernel.util.PropertiesParamUtil;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.kernel.util.UnicodeProperties;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.kernel.util.WebKeys;
import com.liferay.portal.model.Layout;
import com.liferay.portal.model.Portlet;
import com.liferay.portal.security.permission.ActionKeys;
import com.liferay.portal.service.PortletLocalServiceUtil;
import com.liferay.portal.service.permission.PortletPermissionUtil;
import com.liferay.portal.theme.ThemeDisplay;
import com.liferay.portal.util.PortalUtil;
import com.liferay.portlet.PortletConfigFactoryUtil;
import com.liferay.util.portlet.PortletProps;


/**
 * Classe controller utilizada com a finalidade em 
 * remover um anexo mensagem utilizando o metodo de exclusao logica.
 * @author Aiello
 *
 */
public class ConfiguracaoAction implements ConfigurationAction{
	
	private static final Log _log = LogFactoryUtil.getLog(TemplateExcluirActionCommand.class);
	private static final Integer DESTINATARIOS =0;
	public static final String PREFERENCES_PREFIX = "preferences--";
	
	@Override
	public void processAction(
			PortletConfig portletConfig, ActionRequest actionRequest,
			ActionResponse actionResponse)
		throws Exception {

		/*----------------*/
		 String cmd = ParamUtil.getString(actionRequest, Constants.CMD);

		if (!cmd.equals(Constants.UPDATE)) {
			return;
		}

		ThemeDisplay themeDisplay = (ThemeDisplay)actionRequest.getAttribute(
			WebKeys.THEME_DISPLAY);

		UnicodeProperties properties = PropertiesParamUtil.getProperties(
			actionRequest, PREFERENCES_PREFIX);

		String portletResource = ParamUtil.getString(
			actionRequest, "portletResource");

		Layout layout = PortletConfigurationLayoutUtil.getLayout(themeDisplay);

		PortletPermissionUtil.check(
			themeDisplay.getPermissionChecker(), themeDisplay.getScopeGroupId(),
			layout, portletResource, ActionKeys.CONFIGURATION);

		PortletPreferences portletPreferences = actionRequest.getPreferences();

		for (Map.Entry<String, String> entry : properties.entrySet()) {
			String name = entry.getKey();
			String value = entry.getValue();

			portletPreferences.setValue(name, value);
		}

		Map<String, String[]> portletPreferencesMap =
			(Map<String, String[]>)actionRequest.getAttribute(
				WebKeys.PORTLET_PREFERENCES_MAP);

		if (portletPreferencesMap != null) {
			for (Map.Entry<String, String[]> entry :
					portletPreferencesMap.entrySet()) {

				String name = entry.getKey();
				String[] values = entry.getValue();

				portletPreferences.setValues(name, values);
			}
		}

		if (SessionErrors.isEmpty(actionRequest)) {
			try {
				portletPreferences.store();
			}
			catch (ValidatorException ve) {
				SessionErrors.add(
					actionRequest, ValidatorException.class.getName(), ve);

				return;
			}

			SessionMessages.add(
				actionRequest,
				PortalUtil.getPortletId(actionRequest) +
					SessionMessages.KEY_SUFFIX_REFRESH_PORTLET,
				portletResource);

			SessionMessages.add(
				actionRequest,
				PortalUtil.getPortletId(actionRequest) +
					SessionMessages.KEY_SUFFIX_UPDATED_CONFIGURATION);

			String redirect = PortalUtil.escapeRedirect(
				ParamUtil.getString(actionRequest, "redirect"));

			if (Validator.isNotNull(redirect)) {
				actionResponse.sendRedirect(redirect);
			}
		} 
		
		/*----------------*/
		
	}
	@Override
	public String render(PortletConfig portletConfig,
			RenderRequest renderRequest, RenderResponse renderResponse)
			throws Exception {
		
		
		try {
			ThemeDisplay themeDisplay = (ThemeDisplay) renderRequest.getAttribute(WebKeys.THEME_DISPLAY);

			long groupId = themeDisplay.getScopeGroupId();
			
			List<GrupoDestinatario> grupoDestinatario = GrupoDestinatarioLocalServiceUtil
					.findByTipoListaAtivo(DESTINATARIOS, true);
			
			List<GrupoDestinatario> listByGroupId = new ArrayList<>();
			for(int i = 0; i < grupoDestinatario.size();i++){
				if(grupoDestinatario.get(i).getGroupId() == groupId){
					listByGroupId.add(grupoDestinatario.get(i));
				}
			}
			
			renderRequest.setAttribute("grupo", listByGroupId);

			//System.out.println(grupoDestinatario);
			PortletPreferences preferences = renderRequest.getPreferences();
			String grupoDestinatarioId = PrefsParamUtil.getString(preferences, renderRequest, "grupoDestinatarioId", PortletProps.get("configuracao.valor-padrao.IdgrupoMensagem"));
			String emailRemetente = PrefsParamUtil.getString(preferences, renderRequest, "emailRemetente", PortletProps.get("configuracao.valor-padrao.IdgrupoMensagem"));
			GrupoDestinatario GrupoSelecionado = GrupoDestinatarioLocalServiceUtil.getGrupoDestinatario( Long.parseLong(grupoDestinatarioId));
			
			//System.out.println(grupoDestinatarioId);
			
			renderRequest.setAttribute("grupoId", grupoDestinatarioId);
			renderRequest.setAttribute("emailRemetente", emailRemetente);
			renderRequest.setAttribute("nomeGrupo", GrupoSelecionado.getNome());
			
			//System.out.println(GrupoSelecionado.getNome());
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println("=====>" + e.getMessage());
		}
		/*-----------------*/
		PortletConfig selPortletConfig = getSelPortletConfig(renderRequest);

		String configTemplate = selPortletConfig.getInitParameter(
			"config-template");

		if (Validator.isNotNull(configTemplate)) {
			return configTemplate;
		}

		String configJSP = selPortletConfig.getInitParameter("config-template");

		if (Validator.isNotNull(configJSP)) {
			return configJSP;
		}
		/*-----------------*/
		// pagina 
		return "/jsp/cadastro-usuario-config.jsp";
	}
	
	
	protected PortletConfig getSelPortletConfig(PortletRequest portletRequest)
			throws SystemException {

			ThemeDisplay themeDisplay = (ThemeDisplay)portletRequest.getAttribute(
				WebKeys.THEME_DISPLAY);

			String portletResource = ParamUtil.getString(
				portletRequest, "portletResource");

			Portlet selPortlet = PortletLocalServiceUtil.getPortletById(
				themeDisplay.getCompanyId(), portletResource);

			ServletContext servletContext =
				(ServletContext)portletRequest.getAttribute(WebKeys.CTX);

			PortletConfig selPortletConfig = PortletConfigFactoryUtil.create(
				selPortlet, servletContext);

			return selPortletConfig;
		}
}
