/* Copyright 2008 we-lab-doc! (http://www.we-lab-doc.com/)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import javax.mail.internet.MimeMessage
import org.springframework.mail.javamail.MimeMessageHelper


/**
 * @author Shigeru GOUGI
 * @since 0.1
 *        <p/>
 *        Created: February 18, 2008
 */ 
class MailService {
	boolean  transactional = false
	def mailSender
	def mailServiceExceptionReporter
	
	def send (params) {
		return send_(params.from, params.fromPerson, params.to, params.cc, 
				     params.bcc, params.subject, params.bodyText)
	}
	def send (String from, String fromPerson, to,
			  String subject, String bodyText
			) {
		return send_(from , fromPerson, toCol(to), null, null, subject, bodyText)
	}
	def send (String from, String fromPerson, to, cc,
			  String subject, String bodyText
			) {
		return send_(from , fromPerson, toCol, toCol(cc), null, subject, bodyText)
	}
	def send (String from, String fromPerson, to, cc, bcc,
			  String subject, String bodyText
			) {
		return send_(from , fromPerson, toCol(to), toCol(cc), toCol(bcc), subject, bodyText)
	}
	/////////////////////
	void setHost(host) {
		mailSender.setHost(host)
	}
	////////////////////////////////////////////////////////////////////////////////////////
	private def send_(String from, String fromPerson, 
			  Collection tos, Collection ccs, Collection bccs,
			  String subject, String bodyText
			) {

		assert fromPerson != null && from != null && from.length() > 0
		assert tos != null && tos.size() > 0 
		assert subject != null && subject.length() > 0 
		assert bodyText != null && bodyText.length() > 0
		
		def rtStatus
		try {
			MimeMessage message = mailSender.createMimeMessage()
			MimeMessageHelper helper = new MimeMessageHelper(message, "ISO-2022-JP")
			if ( fromPerson != null )
				helper.setFrom(from.trim(), fromPerson.trim() + " " /* スペースは文字化け対策*/)
			else
				helper.setFrom(from.trim())
			helper.setSubject(subject)
			helper.setTo(toAddresses(tos))
			if ( ccs?.size() > 0 ) {
				helper.setCc(toAddresses(ccs))
			}
			if ( bccs?.size() > 0) {
				helper.setBcc(toAddresses(bccs))
			}
			helper.setText(bodyText + "\n" /* '\n' は文字化け対策*/)
			mailSender.send((MimeMessage)message)
			//mailSender.send(message) // こちらだと駄目
			rtStatus = true
		} catch (Exception e) {
			if(mailServiceExceptionReporter)
				// HOOK
				mailServiceExceptionReporter.report(
						[
						 'from':from,
						 'fromPerson':fromPerson,
						 'tos':tos,
						 'ccs':ccs,
						 'bccs':bccs,
						 'subject':subject,
						 'bodyText':bodyText
	  				    ],e)
	  	    else {
	  	    	log.debug("mailServiceExceptionReporter is null")
	  	    	log.error(e)
	  	    }
			rtStatus = e.toString()
		}
		return rtStatus
	}
	private toAddresses(col) {
		String[] array = new String[col.size()]
		int i = 0
		col.each {
			if (it != null)	array[i++] = it.trim()
		}
		return array
	}
	private def toCol(obj) {
		return isCol(obj) ? obj : [obj]
	}
	private boolean isCol(obj) {
		return (obj instanceof Collection)
	}  
}

