package usda.weru.util;

import de.schlichtherle.truezip.file.TFile;
import java.io.IOException;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;
import java.util.Vector;

import javax.activation.FileDataSource;
import javax.activation.DataHandler;

/**
 * 
 */
public class Mailer {

    /**
     * Entry point for testing standalone. Used if this dialog is rum as an independent application.
     * If executed, makes the GUI for MAILER visible.
     * @param args These are the command line arguments passed to the main method.
     */
    static public void main(String args[]) {
        //System.err.println("Sending message to wjr");
        try {
            Mailer.sendMail("mailhost.weru.ksu.edu",
                    "wjr@weru.ksu.edu",
                    "wjr@weru.ksu.edu",
                    "test message from wepsUI mailer",
                    "This is the message\nThis is the message");
        } catch (java.io.IOException e) {
            //System.err.println("sendMail error 1 " + e);
        } catch (javax.mail.internet.AddressException f) {
            //System.err.println("sendMail error 2 " + f);
        } catch (javax.mail.MessagingException g) {
            //System.err.println("sendMail error 3 " + g);
        }
        //System.err.println("Done sending message");

    }

    /**
     * This method prepares the header needed to send the email from within the application
     * when any runtime exception occurs and the current project's "RUN" being worked on by
     * the user needs to be addressed.
     * @param smtp_host The email host ID that is being used to send the mail.
     * @param from Sender's email address
     * @param to Recipient's email address
     * @param subject The subject matter for the email
     * @throws java.io.IOException Generated if any file/data error occurs during sending.
     * @throws javax.mail.internet.AddressException If the sender's or recipient's address doesn't exist,
     * this exception is generated.
     * @throws javax.mail.MessagingException If there is some problem in the mail message itself, we see this exception.
     * @return The message containing all the details including the header info.
     */
    protected static Message prepareHeader(String smtp_host, String from,
            String to, String subject)
            throws IOException, AddressException,
            MessagingException {
        Properties props = new Properties();
        props.put("mail.host", smtp_host);
        Session session = Session.getDefaultInstance(props, null);

        Message msg = new MimeMessage(session);

        InternetAddress addr = new InternetAddress(to);
        msg.addRecipients(Message.RecipientType.TO,
                new InternetAddress[]{addr});

        InternetAddress from_addr = new InternetAddress(from);
        msg.setFrom(from_addr);

        msg.setSubject(subject);

        return msg;
    }

    /**
     * This method sends the email using all the detail provided but without any attachment using just the
     * message part of the email option.
     * @param smtp_host The email host ID that is being used to send the mail.
     * @param from Sender's email address
     * @param to Recipient's email address
     * @param subject The subject matter for the email
     * @param message The message text for the email goes here
     * @throws java.io.IOException Generated if any file/data error occurs during sending.
     * @throws javax.mail.internet.AddressException If the sender's or recipient's address doesn't exist,
     * this exception is generated.
     * @throws javax.mail.MessagingException If there is some problem in the mail message itself, we see this exception.
     */
    public static void sendMail(String smtp_host, String from,
            String to, String subject, String message)
            throws IOException, AddressException,
            MessagingException {
        sendMail(smtp_host, from, to, subject, message, null);
    }

    /**
     * This method sends the email using all the details provided but using attachments such as files, zip
     * files, images, etc besides the message part of the email option.
     * @param smtp_host The email host ID that is being used to send the mail.
     * @param from Sender's email address
     * @param to Recipient's email address
     * @param subject The subject matter for the email
     * @param message The message text for the email goes here
     * @param attach The attachements such as "RUN" file or project's zip file or any other project specific
     * information source of a particular use case responsible for exception generation could
     * be attached
     * @throws java.io.IOException Generated if any file/data error occurs during sending.
     * @throws javax.mail.internet.AddressException If the sender's or recipient's address doesn't exist,
     * this exception is generated.
     * @throws javax.mail.MessagingException If there is some problem in the mail message itself, we see this exception.
     */
    public static void sendMail(String smtp_host, String from,
            String to, String subject, String message, Vector<TFile> attach)
            throws IOException, AddressException,
            MessagingException {
        Message msg = prepareHeader(smtp_host, from, to, subject);

        if (attach != null && attach.size() > 0) {
            MimeMultipart mp = new MimeMultipart();

            MimeBodyPart text = new MimeBodyPart();
            text.setDisposition(Part.INLINE);
            text.setContent(message, "text/plain");
            mp.addBodyPart(text);

            for (int i = 0; i < attach.size(); i++) {
                MimeBodyPart file_part = new MimeBodyPart();
                TFile file = attach.elementAt(i);
                FileDataSource fds = new FileDataSource(file);
                DataHandler dh = new DataHandler(fds);
                file_part.setFileName(file.getName());
                file_part.setDisposition(Part.ATTACHMENT);
                file_part.setDescription("Attached file: " + file.getName());
                file_part.setDataHandler(dh);
                mp.addBodyPart(file_part);
            }
            msg.setContent(mp);
        } else {
            msg.setContent(message, "text/plain");
        }

        Transport.send(msg);
    }

} // Mailer

