/***
	Copyright (c) 2008 CommonsWare, LLC
	
	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.
*/

package com.commonsware.android.service;

import java.security.Security;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Store;

public class MailClient {
	public static String[] getPOP3MessageIds(String server, String user,
												String pw)
		throws MessagingException {
		return(getMessageIds("pop3", server, user, pw));
	}
	
	public static String[] getIMAPMessageIds(String server, String user,
												String pw)
		throws MessagingException {
		return(getMessageIds("imap", server, user, pw));
	}	
	
	private static String[] getMessageIds(String type, String server,
											String user, String pw)
		throws MessagingException {
		String[] result=null;
		
		Session session=Session.getDefaultInstance(System.getProperties());
		Store store=session.getStore(type);
		
		store.connect(server, user, pw);
		
		try {
			Folder folder=store.getFolder("INBOX");
			
			folder.open(Folder.READ_ONLY);

			try {
				Message[] msgs=folder.getMessages();
				
				result=new String[msgs.length];
				
				for (int i=0;i<msgs.length;i++) {
					String[] headers=msgs[i].getHeader("Message-Id");
					
					if (headers==null) {
						result[i]=null;
					}
					else {
						result[i]=headers[0];
					}
				}
			}
			finally {
				folder.close(false);
			}
		}
		finally {
			store.close();
		}
		
		return(result);
	}
}