package ve.gob.cnti.receiver.mail;

import javax.mail.*; 
import javax.mail.internet.InternetAddress; 
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage; 
import javax.mail.internet.MimeMultipart;
import ve.gob.cnti.receiver.utils.ConverFile;
import ve.gob.cnti.receiver.utils.IConverFile;
import ve.gob.cnti.receiver.utils.PropertiesReader;

import java.io.File;
import java.io.IOException;
import java.util.Properties; 
import java.util.logging.Logger;

/*********************************************** 
/* JavaMail SSL + Authentication - Example Code 
/************************************************/ 
public class Mailer implements IMail
{ 
	

	/**
	 * 
	 */
	private static final long serialVersionUID = 6351639313038048762L;

	private static final Logger log = Logger.getLogger(Mailer.class.getName());
	
	PropertiesReader properties=new PropertiesReader();
    private final String EMAIL_SERVER = properties.getProperty("EMAIL_SERVER"); 
    private final String EMAIL_USER_NAME = properties.getProperty("EMAIL_USER_NAME");  
    private final String EMAIL_PASSWORD = properties.getProperty("EMAIL_PASSWORD");  
    private final String EMAIL_TRANSPORT = properties.getProperty("EMAIL_TRANSPORT");    
    private final String EMAIL_FROM_ADDRESS = properties.getProperty("EMAIL_FROM_ADDRESS"); 
    private final String EMAIL_AUTH = properties.getProperty("EMAIL_AUTH"); 
    private final String EMAIL_STARTSSL = properties.getProperty("EMAIL_STARTSSL"); 
    private final String EMAIL_SSL_TRUST = properties.getProperty("EMAIL_SSL_TRUST");
    private final String EMAIL_PORT = properties.getProperty("EMAIL_PORT");
    private final String EMAIL_SERVER_IDENTITY = properties.getProperty("EMAIL_SERVER_IDENTITY");
    

    
    private String toAddress = null; 
    private String cc = null; 
    private String bcc = null; 
    private String fileName=null;
    private String fileExtention=null;
    private boolean htmlFormat = false; 
    private String subject = null; 
    private String body = null; 
    private byte[] receiveFile=null;
	private File  attachFile=null;
	
    public void send() 
    { 
     
    	  Properties parameters=new Properties();    	 
    	  parameters.put("mail."+EMAIL_TRANSPORT+".host", EMAIL_SERVER ); 
    	  parameters.put("mail."+EMAIL_TRANSPORT+".port", EMAIL_PORT ); 
    	  parameters.put("mail."+EMAIL_TRANSPORT+".auth", EMAIL_AUTH); 
    	  parameters.put("mail."+EMAIL_TRANSPORT+".starttls.enable", EMAIL_STARTSSL); 
    	  parameters.put("mail."+EMAIL_TRANSPORT+".ssl.checkserveridentity", EMAIL_SERVER_IDENTITY);
    	  parameters.put("mail."+EMAIL_TRANSPORT+".ssl.trust", EMAIL_SSL_TRUST);

        Session ses  = Session.getInstance(parameters); 
        log.info("enviando correo");
        ses.setDebug(false); 

        try{ 
         
            MimeMessage msg = new MimeMessage(ses); 
            log.info("esta es el correo de "+EMAIL_FROM_ADDRESS);
            msg.setFrom(new InternetAddress(EMAIL_FROM_ADDRESS)); 
            
            if (toAddress != null) 
            { 
               msg.addRecipients(Message.RecipientType.TO, this.getToAddress()); 
            } 
     
            if (cc != null) 
            { 
                msg.setRecipients(Message.RecipientType.CC 
                        ,InternetAddress.parse(this.getCc(), false)); 
            } 
     
            if (bcc != null) 
            { 
                msg.setRecipients(Message.RecipientType.BCC 
                        ,InternetAddress.parse(this.getBcc(), false)); 
            } 
     
            /*if (htmlFormat) 
            { 
                msg.setContent(this.getBody(), "text/html"); 
            } 
            else 
            { 
                msg.setContent(this.getBody(), "text/plain"); 
            } */
            
            log.info("asunto atachado al correo"+this.getSubject());
            log.info("contenido atachado al correo"+this.getBody());
     
            msg.setSubject(this.getSubject()); 
            
				
            
            if(this.getReceiveFile()!=null){
            
            	Multipart multipart = new MimeMultipart();
				
				 
				/*MimeBodyPart messageBodyPart = new MimeBodyPart();
				messageBodyPart.setContent(message, "text/html");*/
				 
				MimeBodyPart attachPart = new MimeBodyPart();
				MimeBodyPart attachPart1 = new MimeBodyPart();
				try {
					IConverFile converFile=new ConverFile();
					this.setAttachFile(converFile.converterBytesToFile(this.getReceiveFile()));
					attachPart.attachFile(this.getAttachFile());
					attachPart.setFileName(fileName);	
									
					if (htmlFormat) 
		            { 
						attachPart1.setContent(this.getBody(), "text/plain; charset=UTF-8");
						
		               
		            } 
		            else 
		            { 
		            	attachPart1.setContent(this.getBody(), "text/plain; charset=UTF-8");
		              
		            } 
					
				
					
					
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				multipart.addBodyPart(attachPart);
				multipart.addBodyPart(attachPart1);	
	            msg.setContent(multipart);
            }else {            
            
	            if (htmlFormat) 
	            { 
	                msg.setContent(this.getBody(), "text/html; charset=UTF-8"); 
	            } 
	            else 
	            { 
	                msg.setContent(this.getBody(), "text/plain; charset=UTF-8"); 
	            } 
            }   
            msg.saveChanges(); 
     
            Transport tr = ses.getTransport(EMAIL_TRANSPORT); 
            tr.connect(EMAIL_SERVER ,EMAIL_USER_NAME, EMAIL_PASSWORD); 
            tr.sendMessage(msg, msg.getAllRecipients()); 
            tr.close(); 
        } 
         
        catch(MessagingException e) 
        { 
            e.printStackTrace(); 
        } 
         
         

    }




	public String getCc() {
		return cc;
	}


	public void setCc(String cc) {
		this.cc = cc;
	}


	public String getBcc() {
		return bcc;
	}


	public void setBcc(String bcc) {
		this.bcc = bcc;
	}


	public String getSubject() {
		return subject;
	}


	public void setSubject(String subject) {
		this.subject = subject;
	}


	public String getBody() {
		return body;
	}


	public void setBody(String body) {
		this.body = body;
	}


	public PropertiesReader getProperties() {
		return properties;
	}


	public void setProperties(PropertiesReader properties) {
		this.properties = properties;
	}


	public String getToAddress() {
		return toAddress;
	}


	public void setToAddress(String toAddres) {
		this.toAddress = toAddres;
	}


	public byte[] getReceiveFile() {
		return receiveFile;
	}


	public void setReceiveFile(byte[] receiveFile) {
		this.receiveFile = receiveFile;
	}


	public File getAttachFile() {
		return attachFile;
	}


	public void setAttachFile(File attachFile) {
		this.attachFile = attachFile;
	}




	public String getFileName() {
		return fileName;
	}




	public void setFileName(String fileName) {
		this.fileName = fileName;
	}




	public String getFileExtention() {
		return fileExtention;
	}




	public void setFileExtention(String fileExtention) {
		this.fileExtention = fileExtention;
	}




	public boolean isHtmlFormat() {
		return htmlFormat;
	}




	public void setHtmlFormat(boolean htmlFormat) {
		this.htmlFormat = htmlFormat;
	} 
    
	
	
	
    
} 

class MyPasswordAuthenticator extends Authenticator 
{ 
   String user; 
   String pw; 

   public MyPasswordAuthenticator (String username, String password) 
   { 
      super(); 
      this.user = username; 
      this.pw = password; 
   } 
   public PasswordAuthentication getPasswordAuthentication() 
   { 
      return new PasswordAuthentication(user, pw); 
   }   
   
   
}  