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

import java.nio.channels.SeekableByteChannel;
import java.util.ArrayList;
import java.util.List;

import javax.mail.internet.InternetAddress;
import javax.portlet.PortletException;
import javax.portlet.PortletPreferences;
import javax.portlet.PortletRequest;
import javax.portlet.PortletResponse;
import javax.portlet.PortletURL;
import javax.servlet.http.HttpServletRequest;

import br.mp.mprj.portal.portlet.gestaomensagens.service.model.EmailDestinatario;
import br.mp.mprj.portal.portlet.gestaomensagens.service.service.EmailDestinatarioLocalServiceUtil;
import br.mp.mprj.portal.portlet.gestaomensagens.util.Constantes;
import br.mp.mprj.portal.portlet.gestaomensagens.util.GerarLink;
import br.mp.mprj.portal.portlet.gestaomensagens.util.GerarListaDecisao;
import br.mp.mprj.portal.portlet.gestaomensagens.util.GestaoMensagensUtil;

import com.liferay.counter.service.CounterLocalServiceUtil;
import com.liferay.mail.service.MailServiceUtil;
import com.liferay.portal.kernel.dao.orm.Session;
import com.liferay.portal.kernel.events.SessionAction;
import com.liferay.portal.kernel.exception.PortalException;
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.mail.MailMessage;
import com.liferay.portal.kernel.servlet.SessionErrors;
import com.liferay.portal.kernel.servlet.SessionMessages;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.kernel.util.PrefsParamUtil;
import com.liferay.portal.kernel.util.PropsKeys;
import com.liferay.portal.kernel.util.PropsUtil;
import com.liferay.portal.kernel.util.SessionParamUtil;
import com.liferay.portal.kernel.util.StringUtil;
import com.liferay.portal.kernel.util.WebKeys;
import com.liferay.portal.kernel.servlet.SessionMessages;


import com.liferay.portal.model.Company;
import com.liferay.portal.model.Group;
import com.liferay.portal.service.CompanyLocalServiceUtil;
import com.liferay.portal.service.GroupLocalServiceUtil;
import com.liferay.portal.theme.ThemeDisplay;
import com.liferay.portal.util.PortalUtil;
import com.liferay.portlet.PortletURLUtil;
import com.liferay.util.ContentUtil;
import com.liferay.util.bridges.mvc.ActionCommand;
import com.liferay.util.portlet.PortletProps;
import com.liferay.util.servlet.SessionParameters;

public class InserirEmailDestinatarioActionCommand implements ActionCommand{

	private static final Log _log = LogFactoryUtil.getLog(InserirEmailDestinatarioActionCommand.class);
	
	public String EMAIL_NOVO_USUARIO = null;
	

	@Override
	public boolean processCommand(PortletRequest portletRequest, PortletResponse response)throws PortletException {
		
		try {
			
		 	if (!ParamUtil.getString(portletRequest, "email_usuario").isEmpty()) {
				EMAIL_NOVO_USUARIO = ParamUtil.getString(portletRequest,"email_usuario");				
			}else{
				return false;
				
			}

			PortletPreferences preferences = portletRequest.getPreferences();
			
			String emailRemetente = PrefsParamUtil.getString(preferences, portletRequest, "emailRemetente", PortletProps.get("configuracao.valor-padrao.IdgrupoMensagem"));
			
			long grupoDestinatarioIdLong = Long.parseLong(PrefsParamUtil.getString(preferences, portletRequest, "grupoDestinatarioId", PortletProps.get("configuracao.valor-padrao.IdgrupoMensagem")));	
						
			List<EmailDestinatario> listaEmail = EmailDestinatarioLocalServiceUtil.findByGrupoDestinatarioId(grupoDestinatarioIdLong);
			
			
			for (EmailDestinatario email : listaEmail){	
				
				if(EMAIL_NOVO_USUARIO.equals(email.getEmail())){
					_log.error("Problemas ao gravar: Usuario tentou cadastrar e-mail já cadastrado");
					SessionErrors.add(portletRequest, "duplicado");
					return false;
				}
			}		
			
		
			final List<EmailDestinatario> listaEmails = loadEmailsDestinatario( grupoDestinatarioIdLong, portletRequest, EMAIL_NOVO_USUARIO);
			
			if (!listaEmails.isEmpty()) {
				for (EmailDestinatario email : listaEmails) {
					EmailDestinatarioLocalServiceUtil.updateEmailDestinatario(email);
				}
			
			}else{
				_log.error("Problemas ao gravar !");
				SessionErrors.add(portletRequest, "Email já cadastrado !");
				return false;
			}
			
			enviaEmail(emailRemetente,"",EMAIL_NOVO_USUARIO,portletRequest);		
			SessionMessages.add(portletRequest, "cadastro-sucesso");			
            return true;
				
			
		} catch (Exception ex) {
			_log.error("Problemas ao gravar:", ex);
			SessionErrors.add(portletRequest, "erro-gravar");

			GestaoMensagensUtil.descartarRascunhos(portletRequest);
			return false;
		}

		

	}
		
	private List<EmailDestinatario> loadEmailsDestinatario(final long grupoDestinatarioId , final PortletRequest req, String email) throws SystemException {
		
		
		List<EmailDestinatario> emailNovoCadastro = new ArrayList<EmailDestinatario>();
		
		EmailDestinatario emailDestinatario2 = EmailDestinatarioLocalServiceUtil.createEmailDestinatario(CounterLocalServiceUtil.increment());
		
		emailDestinatario2.setGrupoDestinatarioId(grupoDestinatarioId);			
		emailDestinatario2.setEmail(email);
		emailNovoCadastro.add(emailDestinatario2);
		return emailNovoCadastro;
		
	
	}
	
	 public static void enviaEmail(String emailRemetente, String emailGestor, String destinatario,PortletRequest portletRequest) throws PortalException, SystemException {
            
       
                        
            try {
                    
        		//Company company = CompanyLocalServiceUtil.getCompanyByMx(PropsUtil.get(PropsKeys.COMPANY_DEFAULT_WEB_ID));
              	
              	//long groupId1 = company.getGroup().getGroupId(); 
              	
              	//Group currentGroup = GroupLocalServiceUtil.getGroup(groupId);
              	
              	
              	ThemeDisplay themeDisplay = (ThemeDisplay) portletRequest.getAttribute(WebKeys.THEME_DISPLAY);

    			long groupId = themeDisplay.getScopeGroupId();
    			Group currentGroup = GroupLocalServiceUtil.getGroup(groupId);
              	
              	String rodapeEndereco = null;
              	String rodapeTexto = null;
              	String url = null;
              	
        		/*----------*/
              
              	
        		 /*---------*/
              	rodapeEndereco = currentGroup.getExpandoBridge().getAttribute("RODAPE_ENDERECO").toString();
              	rodapeTexto = currentGroup.getExpandoBridge().getAttribute("RODAPE_TEXTO").toString();
              	url = currentGroup.getExpandoBridge().getAttribute("HOST_NAME_ID").toString();
        		
                  
                String assunto = "Newsletter - Consumidor Vencedor";
                 
                 String body = ContentUtil.get("template/email/mail-cadastro.html", true);
                  
              	
                  body = StringUtil.replace(body, new String[] {"[$URL$]","[$RODAPE_ENDERECO$]","[$RODAPE_TEXTO$]"},new String[] {url,rodapeEndereco,rodapeTexto});
                  
                  MailMessage mailMessage = new MailMessage();
                 

                  // email de confirmacao para solicitante
                  mailMessage.setBody(body);
                  mailMessage.setSubject(assunto);
                  mailMessage.setHTMLFormat(true);

                  mailMessage.setFrom(new InternetAddress(emailRemetente));
                  mailMessage.setTo(new InternetAddress(destinatario));
                  MailServiceUtil.sendEmail(mailMessage);

                 

            } catch (Exception e) {
                  e.printStackTrace();
            }
      }
	
	
}
	
