/*
 * This file is part of DebGen Biobank Software developed by ASTRID Research.
 * All rights reserved. Reproduction, modification, use or disclosure
 * to third parties without express authority is forbidden.
 *
 * Copyright ASTRID Research Inc., Hungary, 2009-2011.
 *
 * ASTRID Research
 * Headquaters: Csapo utca 42. Debrecen H-4029 HUNGARY
 * Phone: +36-52-533-173        Fax: +36-52-533-174
 * Web: http://www.astrid.hu    E-mail: info@astrid.hu
 *
 * Project name: DebGen Biobank Software project.
 * URLS:
 * Developers: Istvan Zoltan Nagy (istvan.nagy@astrid.hu)
 */
package hu.astrid.debgen.mail.service;

import com.kripto.sendmail.client.SendMail;
import hu.astrid.debgen.server.startup.ApplicationParameters;
import java.net.URL;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Scanner;

/**
 * Sends the e-mail messages of the application
 * @author inagy
 */
public class SendEmailService {

    /**
     * Sends a mail to the recipients using the given template and the dynamic content
     * @param resource The template of the mail message
     * @param dynamicContent The dynamic content which should be replaced in the template
     * @param recipients The list of recipients
     * @throws Exception When the sendmail process isn't possible
     */
    public void sendMail(URL resource, HashMap<String, String> dynamicContent, String... recipients) throws Exception {
        dynamicContent.put("applicationName", ApplicationParameters.getApplicationName());
        dynamicContent.put("applicationUrl", ApplicationParameters.getApplicationURL());

        SendMail sm = new SendMail();
        sm.setUsername("szpetip");
        sm.setPassword("hello");
        sm.setSender("info@astrid.hu");
        sm.setSenderName("DebGen Manager");
        sm.setRecipients(Arrays.asList(recipients));
        sm.setSubject(dynamicContent.get("subject"));
        String message = getEmailMessage(resource, dynamicContent);
        sm.setMessage(message);
        sm.send();
    }

    /**
     * Gets the text of the template document after replacing the dynamic content
     * @param resource The template document
     * @param dynamicContent The dynamic content which is replaced
     * @return The full text of the mail, which should be sent.
     * @throws Exception When the replace or read process fails.
     */
    private String getEmailMessage(URL resource, HashMap<String, String> dynamicContent) throws Exception {
        StringBuilder sb = new StringBuilder();
        Scanner scanner = null;
        try {
            scanner = new Scanner(resource.openStream());
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                sb.append(line + "\n");
            }
        } finally {
            try {
                scanner.close();
            } catch (Exception ex) {
                //IGNORED
                org.apache.log4j.Logger.getLogger(SendEmailService.class).debug("Can't close template scanner? This shouldn't be a problem.");
            }
        }
        String m = sb.toString();
        if (dynamicContent != null) {
            for (Entry<String, String> entry: dynamicContent.entrySet()) {
                m = m.replaceAll("\\$\\{" + entry.getKey() + "\\}", entry.getValue());
            }
        }
        return m;
    }
}
