/*
 * ServletAux.java
 *
 * Created on 10 de Marco de 2005, 12:24
 */

package siprp.pagina;

import javax.activation.*;
import java.io.*;
import java.util.*;

import javax.mail.*;
import javax.mail.internet.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;

import org.apache.commons.mail.*;
import org.apache.velocity.*;
import org.apache.velocity.app.*;

import com.evolute.utils.arrays.*;
/**
 *
 * @author  psantos
 */
public class MailerServlet extends HttpServlet
	implements GlobalConstants
{
	public static final String EMAIL = "email";
	public static final String EMAIL_MARCACAO = "email_marcacao";
	public static final String EMAIL_RECRUTAMENTO = "email_recrutamento";
	
	protected static Hashtable PROPERTIES;
	
	public void init()
	{

		try
		{
			String TEMPLATE_DIR = this.getServletContext().getRealPath( "/" ) + "html/";

			Properties props = new Properties();
			props.setProperty( "file.resource.loader.path", TEMPLATE_DIR );
			Velocity.init( props );
			if( PROPERTIES == null )
			{
				Class.forName(bdDriver);
				Connection con = DriverManager.getConnection( bdUrl, bdUsername, bdPassword );
				Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
				ResultSet2DArray array = new ResultSet2DArray( 
					stmt.executeQuery( "Select name, value FROM properties;" ) );
				PROPERTIES = new Hashtable();
				for( int n = 0; n < array.columnLength(); n++ )
				{
					PROPERTIES.put( array.get( n, 0 ), array.get( n, 1 ) );
				}
				con.close();
			}
		}
		catch( Exception e )
		{
			e.printStackTrace();
		}
	}

	protected String createContent( Hashtable parameters, String[] form_fields, String template )
	{
		VelocityContext context = new VelocityContext();
		StringWriter output = new StringWriter();

		try
		{
			for( int i = 0; i < form_fields.length; i++ )
			{
				context.put( form_fields[ i ], parameters.get( form_fields[ i ] ) );
			}

			Velocity.mergeTemplate( template, Velocity.ENCODING_DEFAULT, context, output );

			return output.toString();
		}
		catch( Exception e )
		{
			e.printStackTrace();
		}

		return null;
	}
	
	protected String showResultPage( boolean success, String success_template, String fail_template )
	{
		VelocityContext context = new VelocityContext();
		StringWriter output = new StringWriter();
		String template;
		if( success )
		{
			template = success_template;
		}
		else
		{
			template = fail_template;
		}
		try
		{
			Velocity.mergeTemplate( template, Velocity.ENCODING_DEFAULT, context, output );
			return output.toString();
		}
		catch( Exception e )
		{
			e.printStackTrace();
		}

		return null;
	}

	protected boolean sendMail( String from, String destination, String subject, String content, boolean html )
	{
		String smtp_server = "localhost";
		String mailer = "Evolute Mailer";

		Properties props = System.getProperties();
		props.put( "mail.smtp.host", smtp_server );

		String content_type = ( html ) ? "text/html" : "text/plain";
		
		Session session = Session.getInstance( props, null );
		Message msg = new MimeMessage( session );
		try
		{
			if( from != null )
			{
				msg.setFrom( new InternetAddress( from ) );
			}
			msg.setRecipients( Message.RecipientType.TO, InternetAddress.parse( destination, true ) );
			msg.setSubject( subject );

			msg.setContent( content.toString(), content_type );

			msg.setHeader( "X-Mailer", mailer );
			msg.setSentDate( new java.util.Date() );
			Transport.send( msg );

			return true;
		}
		catch( Exception e )
		{
			e.printStackTrace();
		}

		return false;
	}
	
	protected boolean sendMail( String from, String destination, String subject, String content, boolean html,
								String filename, byte attachment[], String type )
	{
		String smtp_server = "localhost";
		String mailer = "Evolute Mailer";

		Properties props = System.getProperties();
		props.put( "mail.smtp.host", smtp_server );

		String content_type = ( html ) ? "text/html" : "text/plain";
		
		Session session = Session.getInstance( props, null );
		Message msg = new MimeMessage( session );
		try
		{
			if( from != null )
			{
				msg.setFrom( new InternetAddress( from ) );
			}
			msg.setRecipients( Message.RecipientType.TO, InternetAddress.parse( destination, true ) );
			msg.setSubject( subject );
			msg.setHeader( "X-Mailer", mailer );
			msg.setSentDate( new java.util.Date() );
			
			Multipart multipart = new MimeMultipart();
			BodyPart messageBodyPart = new MimeBodyPart();
			messageBodyPart.setContent( content.toString(), content_type );
			multipart.addBodyPart(messageBodyPart);

			messageBodyPart = new MimeBodyPart();
//			messageBodyPart.setDataHandler(
//				new DataHandler( new ByteArrayDataSource( attachment, "/siprpWeb/test.txt" )));
			messageBodyPart.setContent( attachment, content_type );
			DataSource source = new ByteArrayDataSource(attachment, type);
			messageBodyPart.setDataHandler(
			  new DataHandler(source));
			messageBodyPart.setFileName(filename);
			
			multipart.addBodyPart(messageBodyPart);
		    msg.setContent(multipart);
			
			Transport.send( msg );

			return true;
		}
		catch( Exception e )
		{
			e.printStackTrace();
		}

		return false;
	}

	private String checkParameter( String parameter )
	{
		if( parameter != null && parameter.trim().length() > 0 )
		{
			return parameter.trim();
		}

		return null;
	}

	protected Hashtable parseParameters( Hashtable parameters )
	{
		Hashtable tmp = new Hashtable();
		String[] element;
		String key;
		String new_element;
		for( Enumeration e = parameters.keys(); e.hasMoreElements(); )
		{
			key = ( String ) e.nextElement();
			element = ( String[] ) parameters.get( key );
			if( element != null )
			{
				new_element = checkParameter( element[ 0 ] );
				if( new_element != null )
				{
					tmp.put( key, new_element );
				}
			}
		}

		return tmp;
	}
}
