/*
 * 
 */
package com.fp.bpmlib.mail;

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

import com.fp.common.logger.APPLogger;
import com.fp.dto.Request;

// TODO: Auto-generated Javadoc
/**
 * MailCommand encargada del envío de correos a partir de una regla.
 * 
 * @author gfiallos
 */
public class MailCommand {

    /** El valor de parameters. */
    private final Map<String, Object> parameters;

    /** El valor de request. */
    private final Request request;

    /** El valor de m. */
    private final Mailer m;

    /**
     * Crea una nueva instancia de mail command.
     * 
     * @param pParameters the parameters
     * @throws Exception la exception
     */
    public MailCommand(Map<String, Object> pParameters) throws Exception {
        APPLogger.getLogger().info(pParameters);
        parameters = pParameters;
        request = (Request) parameters.get("request");
        m = new Mailer(request);
    }

    /**
     * Send.
     * 
     * @throws Exception la exception
     */
    public void send() throws Exception {
        this.manageTo();
        m.setSubject((Integer) parameters.get("subject"));
        m.setContent((Integer) parameters.get("content"));
        MailThread mt = new MailThread(m);
        mt.start();
        // this.m.send();
    }

    /**
     * Maneja el campo to.
     * 
     * @throws Exception la exception
     */
    @SuppressWarnings("unchecked")
    private void manageTo() throws Exception {
        List<String> users = (List<String>) parameters.get("user");
        if (users != null) {
            for (String user : users) {
                m.setToUser(user);
            }
        }
        List<String> groups = (List<String>) parameters.get("group");
        if (groups != null) {
            for (String group : groups) {
                m.setToGroup(group);
            }
        }
        List<String> fields = (List<String>) parameters.get("field");
        if (fields != null) {
            for (String field : fields) {
                m.setTo(request.getString(field));
            }
        }
        List<String> ladress = (List<String>) parameters.get("address");
        if (ladress != null) {
            for (String address : ladress) {
                m.setTo(address);
            }
        parameters.remove("address");
        }
    }
}
