package notifiers;

import java.util.List;
import java.util.Map;

import org.apache.commons.mail.EmailAttachment;

import play.mvc.Mailer;
import utils.StringUtil;
import utils.cfg.CfgUtil;

public class Mails extends Mailer {

	static class MailUtil {
		public static void begin() {
			Map<String, Object> map = Mails.infos.get();
			List<String> recipientsList = (List<String>) map.get("recipients");
			if (recipientsList != null && !recipientsList.isEmpty()) {
				recipientsList.clear();
				map.put("recipients", recipientsList);
			}

			List<String> bccsList = (List<String>) map.get("bccs");
			if (bccsList != null && !bccsList.isEmpty()) {
				bccsList.clear();
				map.put("bccs", bccsList);
			}

			List<String> ccsList = (List<String>) map.get("ccs");
			if (ccsList != null && !ccsList.isEmpty()) {
				ccsList.clear();
				map.put("ccs", ccsList);
			}
			List<EmailAttachment> attachmentsList = (List<EmailAttachment>) map.get("attachments");
			if (attachmentsList != null && !attachmentsList.isEmpty()) {
				attachmentsList.clear();
				map.put("attachments", attachmentsList);
			}
			map.put("subject", "");
			map.put("from", "");
			Mails.infos.set(map);
		}

		public static void setFrom(String fullName, String email) {
			Mailer.setFrom(createRecipient(fullName, email));
		}

		public static void addTo(String fullName, String email) {
			Mailer.addRecipient(createRecipient(fullName, email));
		}

		public static String createRecipient(String fullName, String email) {
			return fullName + " <" + email + ">";
		}

		public static void end() {

		}
	}

	public static void sendVerificationCode(String fullName, String username, String verificationCode) {
		MailUtil.begin();
		MailUtil.setFrom(CfgUtil.getString("mail.smtp.fromName", "Testing Tool"),
				CfgUtil.getString("mail.smtp.user", "cinibackend@gmail.com"));
		String name;
		if (StringUtil.isNil(fullName)) {
			name = username;
		} else {
			name = fullName;
		}
		MailUtil.addTo(name, username);
		setSubject("CINI - Conferma la tua mail");
		send(name, verificationCode);
	}

}