/* 
 * 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
*/
 
/* 
 * This software was written by Julian Selley (j.selley@man.ac.uk)
 * whilst at the University of Manchester as a Research Assistant. 
 *
 * The initial code base is copyright by the University of Manchester. 
 * Modifications to the initial code base are copyright of their 
 * respective authors, or their employers as appropriate. Authorship 
 * of the modifications may be determined from the ChangeLog placed 
 * at the end of this file
 */

package uk.ac.man.bioinf.apps.cinema.io; // Package name inserted by JPack

import java.awt.event.ActionEvent;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JOptionPane;
import uk.ac.man.bioinf.apps.cinema.CinemaGuiModule;
import uk.ac.man.bioinf.apps.cinema.CinemaModule;
import uk.ac.man.bioinf.apps.cinema.core.CinemaActionProvider;
import uk.ac.man.bioinf.debug.Debug;
import uk.ac.man.bioinf.io.AlignmentInputParser;
import uk.ac.man.bioinf.io.ParserException;
import uk.ac.man.bioinf.io.ParserExceptionHandler;
import uk.ac.man.bioinf.module.ModuleException;
import uk.ac.man.bioinf.module.ModuleIdentifierList;
import uk.ac.man.bioinf.sequence.alignment.SequenceAlignment;
import uk.ac.man.bioinf.sequence.identifier.Identifier;
import uk.ac.man.bioinf.sequence.identifier.NoIdentifier;


/**
 * This class is abstract and will be extended by any sequence input
 * modules. It merely provides the action stuff for the menu system,
 * and describes an abstract method run by the actionPerformed(...)
 * and implemented by the children of this class.
 *
 *
 * Created: Wed Jun 14 15:26:56 2000
 *
 * @author Julian Selley
 * @version $Id: AbstractSequenceInput.java,v 1.13 2002/04/20 14:59:05 lord Exp $
 */

public abstract class AbstractSequenceInput extends CinemaGuiModule 
  implements CinemaActionProvider
{
  private static final Map parserMap = new HashMap();
  protected AbstractSequenceParserExceptionHandler eh;
  
  public final String[] getAvailableParsers()
  {
    Object[] keys = ((Set)parserMap.keySet()).toArray();
    String[] retn = new String[ keys.length ];
    
    System.arraycopy( keys, 0, retn, 0, keys.length );
    return retn;
  }
  
  public final AlignmentInputParser getParser( String keyOfParser )
  {
    AlignmentInputParser retn = null;
    
    try{
      retn = (AlignmentInputParser)
        (((Class)parserMap.get( keyOfParser)).newInstance());
    }
    catch( InstantiationException ie ){
      if( Debug.debug )
        Debug.both( this, "Input Parser Error", ie );
    }
    catch( IllegalAccessException iae ){
      if( Debug.debug )
        Debug.both( this, "Input Parser Error", iae );
    }

    return retn;
  }
  
  public final String getParserDescription( String keyOfParser )
  {
    return getParser( keyOfParser ).getDescription();
  }
  
  public void load() throws ModuleException
  {
    Properties configProps = getConfigProperties();
    
    for ( Enumeration e = configProps.propertyNames() ; e.hasMoreElements() ;){
      try{
        String parserKey = (String)e.nextElement();
        if( !parserKey.equals( "default" ) ){
          String parserClassName = configProps.getProperty( parserKey );
          parserClassName = parserClassName.substring( 4, parserClassName.length() );
          Class parserClass = getClass().getClassLoader().
            loadClass( parserClassName );
          
          parserMap.put( parserKey, parserClass );
        }
      }
      catch( ClassNotFoundException cnfe ){
        if( Debug.debug )
          cnfe.printStackTrace();
        throw new ModuleException( cnfe );
      }
    }
  }
   
  /**
   * Supplies the action for the menu system/whatever else wishes to
   * invoke this modules action.
   *
   * @return the possible actions
   */
  public Action[] getActions() 
  {
    Action[] rtn = new Action[1];
    
    rtn[0] = new AbstractAction("Open...") {
	public void actionPerformed(ActionEvent event) 
	{
	  SequenceAlignment alignment = openAlignment();
	  
	  setSequenceAlignment( alignment );
	  
	  // if there are parser exceptions ask whether to display them
	  if (eh != null) {
	    ParserException[] parserExceptions = eh.getParserExceptions();
	    if (parserExceptions.length != 0 ) {
              if( parserExceptions.length < 10 ){
                JOptionPane message = new JOptionPane();
                int status = message.showConfirmDialog
                  (getFrame(), 
                   "Sequence errors were detected in parsing, but were dealt with \n" +
                   "by putting a gap in the offending position\n" +
                   "Do you wish to see the errors?\n",
                   "Warning: Sequence errors", 
                   JOptionPane.YES_NO_OPTION,
                   JOptionPane.WARNING_MESSAGE);
                // if selected yes, then display the errors in a
                // separate dialog
                if (status == JOptionPane.YES_OPTION) {
                  // put exceptions into one stringbuffer
                  StringBuffer exceptionStringBuffer = new StringBuffer();
                  for (int i = 0; i < parserExceptions.length; i++) {
                    exceptionStringBuffer.append
                      (parserExceptions[i].getIdentifier().getTitle() + ": " + 
                       parserExceptions[i].getMessage() + "\n");
                  }
                  // display the errors
                  JOptionPane errors = new JOptionPane();
                  errors.showMessageDialog
                    (getFrame(),
                     "The errors were: \n" + exceptionStringBuffer.toString(),
                     "Sequence errors",
                     JOptionPane.WARNING_MESSAGE);
                }
              }
              else{
                JOptionPane message = new JOptionPane();
                message.showMessageDialog
                  ( getFrame(), 
                    "Sequence errors were detected in parsing. These\n" +
                    "have been replaced by gaps. However there were a\n" +
                    "large number so you may be using an unsupported format\n",
                    "Warning: Sequence errors",
                    JOptionPane.WARNING_MESSAGE);
              }
            }
          }
        }
      };

    return rtn;
  }

  /**
   * Obtains the sequence alignment by the relevent method.
   *
   * @return the sequence alignment
   */
  public abstract SequenceAlignment openAlignment();


  /**
   * Sets the parser exception handler.
   *
   * @param eh exception handler
   */
  public void setExceptionHandler
    (AbstractSequenceParserExceptionHandler exceptionHandler) 
  {
    eh = exceptionHandler;
  }
  
  /**
   * Returns the parser exception handler.
   *
   * @return the exception handler
   */
  public ParserExceptionHandler getExceptionHandler() 
  {
    return eh;
  }

  public ModuleIdentifierList getRequiredIdentifiers() 
  {
    return super.getRequiredIdentifiers();
  }
} // AbstractSequenceInput



/*
 * ChangeLog
 * $Log: AbstractSequenceInput.java,v $
 * Revision 1.13  2002/04/20 14:59:05  lord
 * Improved error handling
 *
 * Revision 1.12  2001/07/06 12:38:49  lord
 * Removed debug output
 *
 * Revision 1.11  2001/05/29 13:01:15  lord
 * Filled in method
 *
 * Revision 1.10  2001/05/24 15:38:57  lord
 * Parsers are now configurable. Added save as option.
 *
 * Revision 1.9  2001/04/11 17:04:42  lord
 * Added License agreements to all code
 *
 * Revision 1.8  2001/01/27 16:53:41  lord
 * Removed status information, as this is done seperately now.
 *
 * Revision 1.7  2000/12/05 15:54:37  lord
 * Import rationalisation
 *
 * Revision 1.6  2000/10/13 14:32:54  jns
 * o sorting out a problem with null elements (X) that I had previously
 * had working, but I then messed it up trying to be smart. I have sorted
 * by taking out the actualy formation of the sequence, but supplied the
 * basic elements for creating the sequence.
 *
 * Revision 1.5  2000/09/11 13:20:08  lord
 * Puts alignment source or identifier in the window frame now.
 *
 * Revision 1.4  2000/08/21 17:18:55  jns
 * o input parser exception handler changed to just one exception handler - there
 * dont need to be two
 * o changed menu item name to open rather than open alignment
 *
 * Revision 1.3  2000/08/01 14:53:06  jns
 * o change of name of ParseException ParserException
 *
 * Revision 1.2  2000/06/29 16:10:33  jns
 * o added error code handling
 * o changed exception handler type
 *
 * Revision 1.1  2000/06/16 09:41:55  jns
 * o initial code for a sequence input modules, inc. for the moment just the
 * file sequence input module.
 *
 */
