package com.bizofficer.util.system;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.core.BeanPropertyRowMapper;

import java.io.UnsupportedEncodingException;  
import java.util.Iterator;
import java.util.List;
import java.util.Properties;  
import java.util.logging.Level;  

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.Authenticator;  
import javax.mail.Message;  
import javax.mail.MessagingException;  
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;  
import javax.mail.Session;  
import javax.mail.Transport;  
import javax.mail.internet.InternetAddress;  
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage; 
import javax.mail.internet.MimeMultipart;

@SuppressWarnings("unused")
public class MailUtil{
 
	private static final Logger logger = Logger.getLogger(MailUtil.class);

    private String SMTP_HOST,FROM_ADDRESS,PASSWORD,FROM_NAME, SMTP_SSL_ENABLE;
    private Integer SMTP_PORT;
    
    public MailUtil() {
    	ApplicationProperties appProp = new ApplicationProperties();
		this.SMTP_HOST = appProp.getProperty("smtpHost").trim();
		this.SMTP_PORT = Integer.valueOf(appProp.getProperty("smtpPort").trim());
		this.FROM_ADDRESS = appProp.getProperty("smtpEmail").trim();
		this.PASSWORD = appProp.getProperty("smtpEmailPassword").trim();
		this.FROM_NAME = appProp.getProperty("smtpFromName").trim();		    		
		this.SMTP_SSL_ENABLE=appProp.getProperty("smtpSSLOption").trim();
    		
	}	
    

    
    public boolean sendMail(String[] recipients, String[] bccRecipients, String subject, String message, String[] attachedFiles) {  
        try {  

        	if(this.SMTP_HOST==null || (this.SMTP_HOST!=null && this.SMTP_HOST.length()<1) || this.SMTP_PORT==null){
            	return false;
            }

        	Properties props = new Properties();  
            props.put("mail.smtp.host", SMTP_HOST);  
            props.put("mail.smtp.port", SMTP_PORT);
            props.put("mail.smtp.auth", "true");  
            props.put("mail.debug", "false");  
            props.put("mail.smtp.ssl.enable", SMTP_SSL_ENABLE);  
            
            Session session = Session.getInstance(props, new SocialAuth());  
            Message msg = new MimeMessage(session);  
  
            Address from = new InternetAddress(FROM_ADDRESS, FROM_NAME);
            // this is commented because it was not able to send email to same domain
            ///InternetAddress from = new InternetAddress(FROM_ADDRESS, FROM_NAME);  
            msg.setFrom(from);  
  
            InternetAddress[] toAddresses = new InternetAddress[recipients.length];  
            for (int i = 0; i < recipients.length; i++) {  
                toAddresses[i] = new InternetAddress(recipients[i]);  
            }  
            msg.setRecipients(Message.RecipientType.TO, toAddresses);  
  
            if(bccRecipients!=null){
	            InternetAddress[] bccAddresses = new InternetAddress[bccRecipients.length];  
	            for (int j = 0; j < bccRecipients.length; j++) {  
	                bccAddresses[j] = new InternetAddress(bccRecipients[j]);  
	            }  
	            msg.setRecipients(Message.RecipientType.BCC, bccAddresses);  
            }
            
            msg.setSubject(subject);  
            //msg.setContent(message, "text/html");
            
            // Create the message part
            MimeBodyPart messageBodyPart = new MimeBodyPart();

            // Now set the actual message
            messageBodyPart.setContent(message, "text/html");

            // Create a multipar message
            Multipart multipart = new MimeMultipart();
            
            // Set text message part
            multipart.addBodyPart(messageBodyPart);
            
            if(attachedFiles!=null && attachedFiles.length>0){
	            for(String file : attachedFiles){  
	                MimeBodyPart fileAttachmentBodyPart = new MimeBodyPart();
	                String[] fileArr = file.split("/");
	                String fileName = fileArr[fileArr.length-1]; // Attachment Name 
	                DataSource source = new FileDataSource(file);
	                fileAttachmentBodyPart.setDataHandler(new DataHandler(source));
	                fileAttachmentBodyPart.setFileName(fileName);
	                multipart.addBodyPart(fileAttachmentBodyPart);
	            } 
            }
/*            // Start First Attachment ********************************
            MimeBodyPart fileAttachmentBodyPart = new MimeBodyPart();
            String file = "D:/java-spring-crm-files/files/test-1-51-te.doc"; // path of file to be attached 
            String fileName = "test-1-51-te.doc"; // Attachment Name 
            DataSource source = new FileDataSource(file);
            fileAttachmentBodyPart.setDataHandler(new DataHandler(source));
            fileAttachmentBodyPart.setFileName(fileName);
            multipart.addBodyPart(fileAttachmentBodyPart);
            // End First Attachment ********************************

            // Start Second Attachment ********************************
            MimeBodyPart fileAttachmentBodyPart2 = new MimeBodyPart();
            String file2 = "D:/java-spring-crm-files/files/97-1-26-t.html"; // path of file to be attached 
            String fileName2 = "97-1-26-t.html"; // Attachment Name 
            DataSource source2 = new FileDataSource(file2);
            fileAttachmentBodyPart2.setDataHandler(new DataHandler(source2));
            fileAttachmentBodyPart2.setFileName(fileName2);
            multipart.addBodyPart(fileAttachmentBodyPart2);
            // End Second Attachment ********************************
*/
            // Send the complete message parts
            msg.setContent(multipart, "text/html");
            
            // Send message
            Transport.send(msg);  
            
            return true;  
        } catch (UnsupportedEncodingException ex) {  
            ex.printStackTrace();  
            return false;  
  
        } catch (MessagingException ex) {  
        	ex.printStackTrace();  
            return false;  
        }  
    }  
  
    class SocialAuth extends Authenticator {  
  
        @Override  
        protected PasswordAuthentication getPasswordAuthentication() {  
  
            return new PasswordAuthentication(FROM_ADDRESS, PASSWORD);  
  
        }  
    }  
	
}
