/*
 * CreditCard.java
 * Created on Jun 7, 2005 
 * Author: 	László Felföldi, Etixpert GmbH
 * mail:	laszlo.felfoldi@etixpert.com		
 */
package com.etixpert.evolution.app.mail;

import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.Map;
import java.util.Set;

import javax.mail.*;
import com.sun.mail.smtp.SMTPMessage;
import javax.mail.internet.*;
import javax.activation.*;

public class Mail {
    private String smtpServer;
    private String smtpPort;
    private String smtpUser;
    private String smtpPassword;
    private String from;
    private String from_display_name;
    
    private boolean dsnsuccess;
    private boolean dsnfailure;
    private String  dsn_to;
    
    public class ByteArrayDataSource implements DataSource {
        byte[] bytes;
        String contentType, name;

        ByteArrayDataSource(byte[] bytes, String contentType, String name) {
          this.bytes = bytes;
          this.contentType = contentType;
          this.name = name;
        }

        public String getContentType() {
          return contentType;
        }

        public InputStream getInputStream() {
          return new ByteArrayInputStream(bytes,0,bytes.length);
        }

        public String getName() {
          return name;
        }

        public OutputStream getOutputStream() throws IOException {
          throw new FileNotFoundException();
        }
    }
    
    private class SMTPAuthenticator extends javax.mail.Authenticator
    {
        String username;
        String password;
        
        public PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }
        
        public SMTPAuthenticator(String aUserName, String aPassword) {
            username = aUserName;
            password = aPassword;
        }
    }
    
    public void send(String to, String subject, String body, Map[] attachment) {
        try {
            // Create mail container
            MimeMultipart mp = new MimeMultipart();

	        /// adding source to the mail container
	        MimeBodyPart mbp = new MimeBodyPart();
	        mbp.setText(body);
	        mbp.setDisposition(MimeBodyPart.INLINE);
	        mp.addBodyPart(mbp);
		        
		    for (int i = 0; i < attachment.length; i++) {
			  	MimeBodyPart bp = new MimeBodyPart();
				byte[] bin      = (byte[]) attachment[i].get("content");
			  	String filename = (String) attachment[i].get("file");
			  	String mimeType = (String) attachment[i].get("type");
		
		  		bp.setDisposition(MimeBodyPart.ATTACHMENT);
		
		  		if (filename != null) {
					int    ii    = filename.lastIndexOf("/");
					String fname = ii != -1 ? filename.substring(ii + 1) : filename;
					bp.setFileName(fname);
		  		}
	      
		  		if (bin != null) {
					bp.setDataHandler(new DataHandler(new ByteArrayDataSource(bin, mimeType, filename)));
					mp.addBodyPart(bp);
		  		}
		    }
	
	        // create smtp session
	        java.util.Properties props = System.getProperties();
	    	props.put("mail.smtp.host", smtpServer);
	    	
	    	if (dsnsuccess || dsnfailure) {
	    		String sf = "";
	    		
	    		if (dsnsuccess && !dsnfailure)      sf = "SUCCESS";
	    		else if (dsnfailure && !dsnsuccess) sf = "FAILURE";
	    		else if (dsnsuccess && dsnfailure)  sf = "SUCCESS, FAILURE";
	    		
	    		String specto = "";
	    		
	    		if (!dsn_to.equals("")) {
	    		    specto =  " ORCPT=rfc822;" + dsn_to;
	    		}
	    		
	    		props.put("mail.smtp.reportsuccess", "true");
	    		props.put("mail.smtp.dsn.notify", sf + specto);
	    		props.put("mail.smtp.dsn.ret", "HDRS");
	    	}
	    		
	    	
	   		props.put("mail.smtp.port", smtpPort);
	
	        Session session;
		        
	        if (!smtpUser.equals("")) {
	    		props.put("mail.smtp.auth", "true");
	    		Authenticator auth = new SMTPAuthenticator(smtpUser, smtpPassword);
	    		session            = Session.getDefaultInstance(props, auth); 
	        } else {
	    		session            = Session.getDefaultInstance(props, null);
	        }
	    		 
	        // create message
	        SMTPMessage msg = new SMTPMessage(session);
	
	        // set message parameter
	    	InternetAddress fromAddress = new InternetAddress();
	    	fromAddress.setAddress(from);
	
	        if (!from_display_name.equals("")) { 
	        	fromAddress.setPersonal(from_display_name);
	        }
	        
	        msg.setFrom(fromAddress);
	        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
	        msg.setSubject(subject);
	        msg.setSentDate(new Date());
	
	        // add the content to the message
	        msg.setContent(mp);
	    	props.put("mail.transport.protocol", "smtp");
	        
	    	// send message
	        Transport transport = session.getTransport("smtp");
	    	
//		    TransportListener listener = new TransportListener() {
//		   		   public void messageDelivered(TransportEvent e) {
//		   			 System.out.println("Delivered");
//		   		   }
//		   		   public void messageNotDelivered(TransportEvent e) {
//		   			 System.out.println("Not Delivered");
//		   		   }
//		   		   public void messagePartiallyDelivered(TransportEvent e) {
//		   			 System.out.println("Partially Delivered");
//		   		   }
//		   		 };
//			transport.addTransportListener(listener);
	
	        transport.connect(smtpServer, smtpUser, smtpPassword);
	        msg.saveChanges();
	        transport.sendMessage(msg, msg.getAllRecipients());
        } catch (Exception e) {
            
        }
	}
	
	public void sendByLevel(Set levelIDs, String subject, String body, Map attachment) {
	    
	}

	public void sendByCountry(Set countryIDs, String subject, String body, Map attachment) {

	}
	
	public void sendDownline(Object root, String subject, String body, Map attachement) {
	    
	}

}
