/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 1999-2004 Bull S.A.
 * Contact: jonas-team@objectweb.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 *
 * Initial developer(s): Florent BENOIT & Ludovic BERT
 * --------------------------------------------------------------------------
 * $Id$
 * --------------------------------------------------------------------------
 */

package mailsb;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import javax.naming.InitialContext;
import javax.naming.Context;
import javax.rmi.PortableRemoteObject;

/**
 * Sample for Mailer Session Bean. Usage: java mailsb.ClientMailer
 * @author Florent Benoit
 * @author Ludovic Bert
 */
public class ClientMailer {

    /**
     * Session case
     */
    private static final int SESSION_CASE = 1;

    /**
     * MimePartDatasource case
     */
    private static final int MIMEPARTDS_CASE = 2;

    /**
     * Content of the mail
     */
    private static String content = null;

    /**
     * Constructor. Hide constructor as it is an utility class
     */
    private ClientMailer() {

    }

    /**
     * Read from bufferedReader the text which is given by the user after the
     * given prompt.
     * @param bufferedReader the buffer to read input.
     * @param prompt the prompt asking the user.
     * @return the text given by the user.
     * @throws IOException if it can't the bufferedReader.
     */
    private static String getTextFromUser(BufferedReader bufferedReader, String prompt) throws IOException {

        boolean isSet = false;
        String txt = null;
        while (!isSet) {
            System.out.print(prompt + " :");
            txt = bufferedReader.readLine();
            if (!txt.equals("")) {
                isSet = true;
            } else {
                System.out.println("'" + prompt + "' can't be empty.");
            }
        }
        return txt;
    }

    /**
     * Main method of the class
     * @param args the arguments of the program
     */
public static void main(String[] args) {

        //Check if there are valid args
        if (args.length < 1) {
            System.err.println("Syntax is : java mailsb.ClientMailer <SessionMailer | MimePartDSMailer>");
            System.exit(2);
        }


        int argType = 0;
        if (args[0].equalsIgnoreCase("SessionMailer")) {
            argType = SESSION_CASE;
        } else if (args[0].equalsIgnoreCase("MimePartDSMailer")) {
            argType = MIMEPARTDS_CASE;
        } else {
            System.err.println("Invalid type '" + args[0] + "', valid syntax is : java mailsb.ClientMailer <SessionMailer | MimePartDSMailer>");
            System.exit(2);
        }

        //Get the initial context
        Context initialContext = null;
        try {
            initialContext = new InitialContext();
        } catch (Exception e) {
            System.err.println("Cannot get initial context for JNDI: " + e.getMessage());
            System.exit(2);
        }

        switch (argType) {
        case SESSION_CASE :
            sessionMailer(initialContext);
            break;
        case MIMEPARTDS_CASE :
            if (args.length > 1) {
                content = "Content of mail :";
                for (int i = 1; i < args.length; i++) {
                    content += args[i];
                }
            }
            mimePartDSMailer(initialContext);
            break;
        default :

        }


    }
    /**
     * Deal with the MimePartDSMailer bean
     * @param initialContext the initial context
     */
    private static void mimePartDSMailer(Context initialContext) {

        // Connecting to the mailer bean MailerHome thru JNDI
        MimePartDSMailerHome mimePartDSMailerHome = null;
        try {
            System.out.print("Looking up the Session mailer home...");
            mimePartDSMailerHome = (MimePartDSMailerHome) PortableRemoteObject.narrow(initialContext
                    .lookup("MimePartDSMailerHome"), MimePartDSMailerHome.class);
            System.out.println("OK !");
        } catch (Exception e) {
            System.out.println("failed !");
            System.err.println("Cannot lookup MimePartDSMailerHome: " + e.getMessage());
            System.exit(2);
        }

        // MimePartDSMailerBean creation
        MimePartDSMailer mimePartDSMailer = null;
        try {
            System.out.print("Creating a MimePartDS mailer bean ...");
            mimePartDSMailer = mimePartDSMailerHome.create("MimePartDS mailer");
            System.out.println("OK !");
        } catch (Exception e) {
            System.out.println("failed !");
            System.err.println("Cannot create MimePartDSMailerBean: " + e.getMessage());
            System.exit(2);
        }

        if (content == null) {
            //Read the value from the user
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));

            try {
                System.out.println("Content of the mail (Only one line)");
                content = getTextFromUser(bufferedReader, "Content");
            } catch (IOException e) {
                System.err.println("Cannot read line from the bufferedReader : " + e.getMessage());
                System.exit(2);
            }
        }

        //Set the message with a recipient, a subject and a content
        try {
            System.out.print("Setting the message with given content '" + content + "'...");
            mimePartDSMailer.setMessage(content);
            System.out.println("OK !");
        } catch (Exception e) {
            System.out.println("failed !");
            System.err.println("Cannot set args of the message : " + e);
            System.exit(2);
        }

        //And send the message
        try {
            System.out.print("Sending the message...");
            mimePartDSMailer.send();
            System.out.println("OK !");
        } catch (Exception e) {
            System.out.println("Failed !");
            System.err.println("Cannot send the message with MailerBean:" + e);
            System.exit(2);
        }
    }

    /**
     * Deal with the SessionMailer bean
     * @param initialContext the initial context
     */
    private static void sessionMailer(Context initialContext) {
        // Connecting to the mailer bean MailerHome thru JNDI
        SessionMailerHome sessionMailerHome = null;
        try {
            System.out.print("Looking up the Session mailer home...");
            sessionMailerHome = (SessionMailerHome) PortableRemoteObject.narrow(initialContext
                    .lookup("SessionMailerHome"), SessionMailerHome.class);
            System.out.println("OK !");
        } catch (Exception e) {
            System.out.println("failed !");
            System.err.println("Cannot lookup MailerHome: " + e.getMessage());
            System.exit(2);
        }

        // MailerBean creation
        SessionMailer sessionMailer = null;
        try {
            System.out.print("Creating a session mailer bean...");
            sessionMailer = sessionMailerHome.create("mailer");
            System.out.println("OK !");
        } catch (Exception e) {
            System.out.println("failed !");
            System.err.println("Cannot create MailerBean: " + e.getMessage());
            System.exit(2);
        }

        String toRecipient = null;
        String subject = null;
        String content = null;

        //Read the value from the user
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));

        try {
            System.out.println("Recipient is the 'to' field of a mail");
            toRecipient = getTextFromUser(bufferedReader, "TO");

            System.out.println("Subject of the mail");
            subject = getTextFromUser(bufferedReader, "Subject");

            System.out.println("Content of the mail (Only one line)");
            content = getTextFromUser(bufferedReader, "Content");

        } catch (IOException e) {
            System.err.println("Cannot read line from the bufferedReader : " + e.getMessage());
            System.exit(2);
        }

        //Set the message with a recipient, a subject and a content
        try {
            System.out.print("Setting the message with given args...");
            sessionMailer.setMessage(toRecipient, subject, content);
            System.out.println("OK !");
        } catch (Exception e) {
            System.out.println("failed !");
            System.err.println("Cannot set args of the message : " + e);
            System.exit(2);
        }

        //And send the message
        try {
            System.out.print("Sending the message...");
            sessionMailer.send();
            System.out.println("OK !");
        } catch (Exception e) {
            System.out.println("Failed !");
            System.err.println("Cannot send the message with MailerBean:" + e);
            System.exit(2);
        }
    }

}