/**
 * Flogman (Foto bLOG, Mail is All you Need)
 * Copyright (C) 2003 Junya Ishihara (http://flogman.sourceforge.net)
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

package net.sourceforge.flogman;
import java.util.*;
import java.io.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

public class GetMessage {
  private String[] subject;
  private String[] filename;
  private String[] from;
  private int messagelength;

  public GetMessage(String host, String username, String password) throws Exception{

    // Create empty properties
    Properties props = new Properties();

    // Get session
    Session session = Session.getInstance(props, null);
    //session.setDebug(true);

    // Get the store
    Store store = session.getStore("pop3");

    // Connect to store
    store.connect(host, username, password);

    // Get folder
    Folder folder = store.getFolder("INBOX");

    // Open read-write
    folder.open(Folder.READ_WRITE);

    BufferedReader reader = new BufferedReader (
      new InputStreamReader(System.in));

    // Get directory
    Message message[] = folder.getMessages();
    messagelength = message.length;

    if (messagelength > 0) {
      Flogman.cat.info("You have " + message.length + " messages.");
      subject = new String[messagelength];
      filename = new String[messagelength];
      from = new String[messagelength];

      for (int i=0, n=message.length; i<n; i++) {

        // Display from field and subject
	subject[i] = message[i].getSubject();
	if (message[i].getFrom() != null) {
          from[i] = (message[i].getFrom()[0]).toString();
	}

        Flogman.cat.debug("Content-Type:" + message[i].getContentType());
	
        if (message[i].isMimeType("multipart/*")) {
          // Get Attachment
          Multipart mp = (Multipart)message[i].getContent();
          for (int j=0, m=mp.getCount(); j<m; j++) {
            Part part = mp.getBodyPart(j);
            String disposition = part.getDisposition();

            if ((disposition != null) && 
              ((disposition.equals(Part.ATTACHMENT)) || 
              (disposition.equals(Part.INLINE)))) {
              MyUtility.saveFile(Flogman.prop.getProperty("upload_file_location") + "/" + part.getFileName(), part.getInputStream());
              filename[i] = part.getFileName();
            }
          }
	} else if (message[i].isMimeType("image/*")) {
          Flogman.cat.info("MimeType is image.");
          MyUtility.saveFile(Flogman.prop.getProperty("upload_file_location") + "/" + message[i].getFileName(), message[i].getInputStream());
          filename[i] = message[i].getFileName();
	} else if (message[i].isMimeType("video/*")) {
          Flogman.cat.info("MimeType is video.");
          MyUtility.saveFile(Flogman.prop.getProperty("upload_file_location") + "/" + message[i].getFileName(), message[i].getInputStream());
          filename[i] = message[i].getFileName();
	} else {
	  Flogman.cat.info("No attachment or attachment filetype is not image or video.");
	}


        // Delete message
        if ((Flogman.prop.getProperty("debug_not_delete_mail","false")).equals("true")) {
          message[i].setFlag(Flags.Flag.DELETED, false);
          Flogman.cat.debug("Message was not deleted from POP3 server.");
        } else {
          message[i].setFlag(Flags.Flag.DELETED, true);
          Flogman.cat.debug("Message was deleted from POP3 server.");
        }
      }
    } else {
      Flogman.cat.info("You have no message.");
    }

    // Close connection
    folder.close(true);
    store.close();
  }

  public int getNumberOfMessages() {
    return messagelength;
  }

  public String getFirstSubject() {
    return subject[0];
  }

  public String[] getSubjectArray() {
    return subject;
  }

  public String getFirstFilename() {
    return filename[0];
  }

  public String[] getFilenameArray() {
    return filename;
  }

  public String[] getFromArray() {
    return from;
  }

  public static void main (String args[]) throws Exception {
    GetMessage gm = new GetMessage(args[0], args[1], args[2]);
    System.out.println("*****" + gm.getNumberOfMessages() + "****");
    System.out.println("*****" + gm.getFirstSubject() + "****");
    System.out.println("*****" + gm.getFirstFilename() + "****");
    String[] subject = gm.getSubjectArray();
    String[] filename = gm.getFilenameArray();

    for (int i=0, n=gm.getNumberOfMessages(); i<n; i++) {
      System.out.println("*****" + subject[i] + "," + filename[i] + "****");
    }
  }
}
