/*
 * COPYRIGHT (c) 1998-1999 Jan-Henrik Haukeland, http://www.tildeslash.com/
 */

package ts.biff;

import java.util.*;
import java.io.*;

import ts.mail.*;
import ts.config.*;


/**
 * This class contains a collection of methods for handling
 * mail messages.
 *
 * @author  Jan-Henrik Haukeland &lt;hauk@tildeslash.com&gt;
 * @version $Id: MailUtil.java,v 1.2 1999/11/26 00:30:34 hauk Exp $
 *
 */
public final class MailUtil 
{


  private MailUtil() {}


  
  /**
   * Get user prefered Fetch Agent
   * @return FetchAgent
   * @exception ConfigException If invalid protocol
   */
  public static FetchAgent getFetchAgent() throws ConfigException
  {
    FetchAgent agent= null;
    String     proto= Config.get("fetch.protocol");


    if ( ! Constant.inFETCH_PROTOCOLS(proto) )
	throw new ConfigException("Does not recognize protocol: " + 
				  proto +  " for fetching mail");
 

    if ( proto.equals(Constant.MBOX_PROTO) ) 
    {
      String f= Config.get("file.separator");
      String d= Config.get("mbox.spool");
      int    l= d.length()-1;
      
      String spooldir= d.substring(l).equals(f) ? d : d + f;
      
      agent= new MboxAgent(spooldir + Config.get("user.name"));
    }
    else if ( proto.equals(Constant.POP3_PROTO) ) 
    {
      try {
	Pop3Agent p= new Pop3Agent(Config.get("pop.server"),
				   Config.getint("pop.server.port"));
	p.setAuth(Config.get("pop.uname"), Config.get("pop.password"));
	p.setNumLines(Config.getint("maxmailbodylines"));
	agent= p;
      } catch (Exception e) {
	throw new ConfigException("Pop3 error: "+
				  e.getMessage());
      }
    }
    
    return agent;
  }



  /**
   * Returns a String array with only valid wanted mail header 
   * fields read from Config. If an invalid field was found
   * print a warning.
   * @return a String array with guaranteed valid mail header fields
   */
  public static String[] getSelectedHeaderFields()
  {
    String[] t= Config.getValues("mail.table.wanted.fields");
    Vector   v= new Vector(t.length);
    
    for (int i= 0; i<t.length; i++) {
      if ( ! Constant.inMAIL_HEADERS(t[i]) )
	  printWarningForField(t[i]);
      else 
	  v.addElement(t[i]);
    }
    Object o[]= Util.convertToArray(v);
    String s[]= new String[o.length];
    for ( int i= 0; i<o.length; i++ )
	s[i]= (String)o[i];

    return s;
  }



  /**
   * Return User prefered MailTable Header fields. This method
   * and the method below <I>getMail</I> must match exactly
   * the fields extracted.
   * @return A vector containing user prefered header fields 
   */
  public static Vector getTableTitles()
  {
    Vector titles= new Vector();

    // Mailid is always added. Will be a hidden field
    titles.addElement(Constant.MAIL_ID);
    
    // Should we numerate each record in the table
    if ( Config.getboolean("mail.table.numerate") )
	titles.addElement(Config.get("Numerate.name","#"));

    String[] t= getSelectedHeaderFields();
    for ( int i= 0; i< t.length; i++ )
	titles.addElement(t[i]);
  
    return titles;
  }




  /**
   * This method parses the submited Vector with MailModel objects and
   * extract and returns those fields that we are interested in.
   *
   * @param  mailmodels A Vector containing MailModel objects
   * @return A Vector with Field values that could be used by a TsTableModel
   */
  public static Vector getMail(Vector mailmodels)
  {
    Vector mails=  mailmodels;
    if ( mails == null ) return (Vector)null;

    Vector fields= new Vector(mails.size());
    
    int numerator= 0;
    for ( Enumeration e= mails.elements(); e.hasMoreElements();) {
      MailModel m= (MailModel)e.nextElement();
      Vector    v= new Vector();
      String[]  t= getSelectedHeaderFields();

      v.addElement(m.getIdField()); // Mail-id is always added and hidden
      
      if ( Config.getboolean("mail.table.numerate") )
	  v.addElement(new Integer(++numerator));
      
      for ( int i= 0; i<t.length; i++ ) 
      {
	if ( t[i].equals(Constant.MAIL_ID) )
	    v.addElement(m.getIdField());
	
	else if ( t[i].equals(Constant.MAIL_DATE) )
	    v.addElement(m.getDateField());
	
	else if ( t[i].equals(Constant.MAIL_FROM) )
	    v.addElement(m.getFromField());
	
	else if ( t[i].equals(Constant.MAIL_REPLY) )
	    v.addElement(m.getReplyToField());

	else if ( t[i].equals(Constant.MAIL_TO) )
	    v.addElement(m.getToField());
	
	else if ( t[i].equals(Constant.MAIL_SUBJECT) )
	    v.addElement(m.getSubjectField());
	
	else if ( t[i].equals(Constant.MAIL_ORGANIZATION) )
	    v.addElement(m.getOrganizationField());
      }
	
      fields.insertElementAt(v,0);
      
    }
    
    return fields;
   
  }

  
  private static void printWarningForField(String field)
  {
    System.err.println("Warning, requested mail field ("+
		       field + ") is not a legal field "+
		       "and will not be used");
  }
 
}
