package org.wikiwebserver.util;

import javax.mail.*;
import javax.mail.internet.*;
import java.util.*; 
import java.io.*;

import org.wikiwebserver.core.Privilege;
import org.wikiwebserver.core.WareHouse;
import org.wikiwebserver.handler.http.FormData;
import org.wikiwebserver.handler.http.HTTPException;
import org.wikiwebserver.handler.http.HTTPHandler;
import org.wikiwebserver.handler.http.interfaces.HTTPResponder;

import page.tools.entity.User;

public class MailSender implements HTTPResponder {
    
	
    public Object respond(HTTPHandler conn) throws IOException {
        
        String email = null;
        
        FormData formData = conn.getRequest().getFormData();
        if (formData != null) {
            email = formData.getFirst("email");
            if (email == null || email.length() == 0) {
                throw new HTTPException(500, "No email in posted data");
            }   
            User user = User.getUser(conn.getRequest());
            if (user.getPrivilege().isBelow(Privilege.USER)) {
                throw new HTTPException(500, "You must be signed in to send test email");
            }
            
            postMail(email, "Test email sent from WikiWebServer", 
                    "See email headers for more details",
                    "no-reply@wikiwebserver.org", conn);            
        }
        
        StringBuilder body = new StringBuilder();        
        if (email == null) {
            
            body.append("<h1>Mail sending test</h1>" +
                        "<p>Specify an email address to send a test email</p>");            
            
            String action = conn.getRequest().getUrl();  
            body.append("<form method='post' action='" + action + "' charset='UTF-8'>"); 
            body.append("<p>Recpient Email Address:</p>");
            String a = WareHouse.escapeHTMLEntities("");
            body.append("<input id='action' type='text' name='email' size='60' value='" + a + "'/>");
            
            body.append("<p><input class='submit' type='submit' name='submit' value='Send'/></p>");     
            body.append("</form>"); 
        }
        else {
            body.append("<h1>Email sent</h1>"); 
            body.append("<p>A test email has been sent to " + email + "</p>");            
            
        }

        return body.toString();
    }  
    
    public void postMail(String recipient, String subject, String message, String from, 
            HTTPHandler conn) throws HTTPException {

        postMail(new String[] { recipient }, subject, from, message, conn);     
    }
    
    
    public void postMail(String[] recipients, String subject, String message, String from, 
                         HTTPHandler conn) throws HTTPException {
        
        String browserID = conn.getRequest().getHeaders().getRequestCookies().get("browserID");
        if (browserID != null && browserID.contains("Bot")) {
            HTTPException httpe = new HTTPException(403, "Bad robot, go away");
            throw httpe;
        }
        
        for (String email : recipients) {
            try {
                Validator.validateEmail(email);
            } catch (ValidationError ex) {
                HTTPException httpe = new HTTPException(500, ex.getMessage());
                httpe.initCause(ex);
                throw httpe;
            } catch (Exception ex) {
                // oh well!
            }
        }
        
        try {
            doMailPost(recipients, subject, from, message, conn);
        }
        catch (MessagingException ex) {
            ex.printStackTrace();
            HTTPException httpe = new HTTPException(500, "Failed to send email");
            httpe.initCause(ex);
            throw httpe;
        }        
    }
    
    private void doMailPost(String[] recipients, String subject, String message, String from, 
                            HTTPHandler conn) throws MessagingException {
        
        boolean debug = false;

        // Set the host smtp address
        Properties props = new Properties();
        props.put("mail.smtp.host", "localhost");

        // create some properties and get the default Session
        Session session = Session.getDefaultInstance(props, null);
        session.setDebug(debug);

        // create a message
        Message msg = new MimeMessage(session);

        // set the from and to address
        InternetAddress addressFrom = new InternetAddress(from);
        msg.setFrom(addressFrom);

        InternetAddress[] addressTo = new InternetAddress[recipients.length]; 
        for (int i = 0; i < recipients.length; i++) {
            addressTo[i] = new InternetAddress(recipients[i]);
        }
        msg.setRecipients(Message.RecipientType.TO, addressTo);
       

        // Add lots of logging information, to make tracing easier
        String realRequestIP = conn.getInetAddress().getHostAddress();
        msg.addHeader("WikiWebServerRequestIP", realRequestIP);
        String threadID = Thread.currentThread().getName();
        msg.addHeader("WikiWebServerThreadID", threadID);
        String requestID = conn.getRequest().getRequestID();
        msg.addHeader("WikiWebServerRequestID", requestID);
        String browserID = conn.getRequest().getHeaders().getRequestCookies().get("browserID");
        if (browserID != null) {
            msg.addHeader("WikiWebServerBrowserID", browserID);
        }
        User user = User.getUser(conn.getRequest());
        if (user != null) {
            msg.addHeader("WikiWebServerUserID", user.getId());
            msg.addHeader("WikiWebServerUserEmail", user.getEmail());
        }        

        // Setting the Subject and Content Type
        msg.setSubject(subject);
        msg.setContent(message, "text/plain");
        Transport.send(msg);
    }    
}
