/**
 * Company:      KRANKIKOM
 * @author Paulo Gaspar
 */
import java.util.Properties;
import java.io.File;
import java.io.IOException;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.Session;
import javax.mail.Message;
import javax.mail.BodyPart;
import javax.mail.Multipart;
import javax.mail.SendFailedException;
import javax.mail.MessagingException;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.AddressException;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.DirectoryScanner;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.types.EnumeratedAttribute;

import org.apache.tools.ant.taskdefs.MatchingTask;


public class SendMailTask extends MatchingTask
{   protected String   m_smtpHost  = null;
    protected String   m_from      = null;
    protected String   m_to        = null;
    protected String   m_cc        = null;
    protected String   m_bcc       = null;
    protected String   m_subject   = null;
    protected String   m_text      = "";
    protected File     m_textFile  = null;

    private  File      m_dir;

    public SendMailTask()
    { super();
    }

    /**
     * Set the source dir to find the source text files.
     */
    public void setDir(File i_value)
    { m_dir = i_value;    }

    public void setSmtphost(String i_value)
    { m_smtpHost = i_value;  }

    public void setFrom(String i_value)
    { m_from      = i_value;  }

    public void setTolist(String i_value)
    { m_to        = i_value;  }

    public void setCclist(String i_value)
    { m_cc        = i_value;  }

    public void setBcclist(String i_value)
    { m_bcc       = i_value;  }

    public void setSubject(String i_value)
    { m_subject   = i_value;  }

    public void setTextfile(File i_textFile)
    { m_textFile = i_textFile;  }

    public void setText(String i_value)
    { m_text      = i_value + "\n";  }


    public void addText(String i_value)
    { m_text += i_value.trim() + "\n";  }


    /**
     * Executes the task.
     */
    public void execute() throws BuildException
    {
        // first off, make sure that we've got a srcdir and destdir

        if (m_dir == null)
          throw new BuildException("srcdir attribute must be set!");
        if (!m_dir.exists())
          throw new BuildException("srcdir does not exist!");
        if (!m_dir.isDirectory())
          throw new BuildException("srcdir is not a directory!");

//        // log options used
//        log("options:" +
//            " cr=" + (addcr==1 ? "add" : addcr==0 ? "asis" : "remove") +
//            " tab=" + (addtab==1 ? "add" : addtab==0 ? "asis" : "remove") +
//            " eof=" + (ctrlz==1 ? "add" : ctrlz==0 ? "asis" : "remove") +
//            " tablength=" + tablength,
//            Project.MSG_VERBOSE);

        try
        { if (null == m_text)
            m_text = "";

          DirectoryScanner ds = super.getDirectoryScanner(m_dir);
          String[] fileNames = ds.getIncludedFiles();

          sendMail( m_smtpHost, m_from, m_to, m_cc, m_bcc, m_subject,
                    m_text, (null == m_textFile) ? null : m_textFile.getAbsolutePath(),
                    fileNames
                  );
        }
        catch(Exception e)
        { new BuildException(e);
        }
    }



    private static DataHandler newFileDataHandler(String i_fileName)
    { FileDataSource fds = new FileDataSource(i_fileName);
      return new DataHandler(fds);
    }

    private static boolean strHasSomething(String i_str)
    { return (null != i_str) && (i_str.trim().length() > 0);
    }

    private static String dbgStr(String i_str)
    { return (null == i_str) ? "*NULL*" : i_str;
    }

    private static void dbg(String i_varName, String i_value)
    { System.out.println("  " + i_varName + " = " + dbgStr(i_value));
    }

    private static void dbgArray(String i_varName, String[] i_value)
    { if ((null == i_value) || (i_value.length <= 0))
        dbg(i_varName, null);
      else
        for (int i = 0; i < i_value.length; i++)
          dbg(i_varName + "[" + i + "]", i_value[i]);
    }


    public static void sendMail( String   i_smtpHost,
                                 String   i_from, String i_to, String i_cc, String i_bcc,
                                 String   i_subject,
                                 String i_text, String i_textFileName,  // only one of them will be used
                                                                        // w/ priority for i_textFileName
                                 String[] i_fileNames
                               )
    throws IOException, AddressException, SendFailedException, MessagingException
    {

      if (true)
      { System.out.println("***** sendMail() called *****");
        dbg("i_smtpHost    ", i_smtpHost);
        dbg("i_from        ", i_from);
        dbg("i_to          ", i_to);
        dbg("i_cc          ", i_cc);
        dbg("i_bcc         ", i_bcc);
        dbg("i_subject     ", i_subject);
        dbg("i_text        ", i_text);
        dbg("i_textFileName", i_textFileName);
        System.out.println();
        dbgArray("i_fileNames   ", i_fileNames);
        System.out.println();

        return;
      }


      // Create the JavaMail session
      Properties properties = System.getProperties();
      properties.put("mail.smtp.host", i_smtpHost);
      Session session = Session.getInstance(properties, null);

      // Construct the message
      MimeMessage message = new MimeMessage(session);

      message.setFrom(new InternetAddress(i_from));

      if (strHasSomething(i_to))
        message.setRecipients(Message.RecipientType.TO,  InternetAddress.parse(i_to));
      if (strHasSomething(i_cc))
        message.setRecipients(Message.RecipientType.CC,  InternetAddress.parse(i_cc));
      if (strHasSomething(i_bcc))
        message.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(i_bcc));

      message.setSubject(i_subject);

      if (null == i_text)
        i_text = "";

      if ((null != i_fileNames) && (i_fileNames.length > 0))
      { Multipart mp = new MimeMultipart();
        { MimeBodyPart mbp = new MimeBodyPart();
          if (strHasSomething(i_textFileName))
            mbp.setDataHandler(newFileDataHandler(i_textFileName));
          else
            mbp.setText(i_text);
          mp.addBodyPart(mbp);
        }
        for (int i = 0; i < i_fileNames.length; i++)
        { String fn = i_fileNames[i];
          File file = new File(fn);

          MimeBodyPart mbp = new MimeBodyPart();

          // attach the file to the message
          mbp.setDataHandler(newFileDataHandler(fn));
          mbp.setFileName(fn);
          mp.addBodyPart(mbp);
        }  // for
        // add the Multipart to the message
        message.setContent(mp);
      }  // if
      else
      { if (strHasSomething(i_textFileName))
        { message.setDataHandler(newFileDataHandler(i_textFileName));
          message.setFileName(i_textFileName);
        }
        else
          message.setText(i_text);
      }

      // send the message
      Transport.send(message);
    }
}
