package com.ozacc.mail.mailet;

import java.util.ArrayList;
import java.util.List;

import javax.mail.internet.InternetAddress;

import org.apache.log4j.BasicConfigurator;

import junit.framework.TestCase;

import com.ozacc.mail.fetch.ReceivedMail;
import com.ozacc.mail.mock.MockFetchMailPro;

/**
 * MailetRunnerのテストケース。
 * 
 * @author Tomohiro Otsuka
 * @version $Id: MailetRunnerTest.java,v 1.1.2.1 2005/02/06 13:53:54 otsuka Exp $
 */
public class MailetRunnerTest extends TestCase {

	private MailetRunner mailetRunner;

	/*
	 * @see TestCase#setUp()
	 */
	protected void setUp() throws Exception {
		super.setUp();
		BasicConfigurator.configure();

		MockFetchMailPro fetchMailPro = new MockFetchMailPro();
		fetchMailPro.setupGetMails(getSampleMails());

		Mailet mailet = getSubjectOutputMailet();
		Matcher matcher = getExampleComAddressMatcher();
		List matcherList = new ArrayList();
		matcherList.add(matcher);
		MailetWrapper mw = new MailetWrapper(mailet, matcherList);
		List mwList = new ArrayList();
		mwList.add(mw);
		mwList.add(mw);

		mailetRunner = new MailetRunner();
		mailetRunner.setFetchMailPro(fetchMailPro);
		mailetRunner.setMailetWrapperList(mwList);
	}

	/**
	 * @return 
	 */
	private ReceivedMail[] getSampleMails() {
		List list = new ArrayList();
		ReceivedMail m1 = new ReceivedMail();
		m1.setSubject("m1 - 出力されます。");
		m1.addTo("to@example.com");
		list.add(m1);
		ReceivedMail m2 = new ReceivedMail();
		m2.setSubject("m2 - 出力されません。");
		m2.addTo("to@example.net");
		list.add(m2);
		ReceivedMail m3 = new ReceivedMail();
		m3.setSubject("m3 - 出力されます。");
		m3.addTo("to@example.net");
		m3.addTo("to@example.com");
		list.add(m3);
		return (ReceivedMail[])list.toArray(new ReceivedMail[list.size()]);
	}

	/**
	 * @return 
	 */
	private Matcher getExampleComAddressMatcher() {
		Matcher m = new Matcher() {

			public boolean match(ReceivedMail mail) {
				InternetAddress[] toAddresses = mail.getTo();
				for (int i = 0; i < toAddresses.length; i++) {
					InternetAddress address = toAddresses[i];
					if (address.getAddress().equalsIgnoreCase("to@example.com")) {
						return true;
					}
				}
				return false;
			}
		};
		return m;
	}

	/**
	 * @return 
	 */
	private Mailet getSubjectOutputMailet() {
		return new Mailet() {

			public void service(ReceivedMail mail) {
				System.out.println(mail.getSubject());
			}
		};
	}

	/*
	 * @see TestCase#tearDown()
	 */
	protected void tearDown() throws Exception {
		super.tearDown();
		BasicConfigurator.resetConfiguration();
	}

	public void testRun() {
		mailetRunner.run();
	}

}