/* 
 * 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.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import uk.ac.man.bioinf.debug.Debug;
import uk.ac.man.bioinf.io.AlignmentInputParser;
import uk.ac.man.bioinf.sequence.alignment.SequenceAlignment;
import uk.ac.man.bioinf.sequence.identifier.FileSource;
import uk.ac.man.bioinf.sequence.identifier.Identifier;
import uk.ac.man.bioinf.sequence.identifier.SimpleIdentifier;


/**
 * FileSequenceInput is a that module covers sequence input into
 * Cinema via files. It extends the abstract sequence input module
 * which provides the basics of any sequence input method into
 * Cinema. It is currently Cinema only the abstract sequence input
 * module extends the Cinema GUI module.
 *
 *
 * Created: Thu Jun 15 15:07:12 2000
 *
 * @author Julian Selley
 * @version $Id: FileSequenceInput.java,v 1.15 2002/04/20 14:58:56 lord Exp $
 */

public class FileSequenceInput extends AbstractSequenceInput
{
  private JFileChooser chooser = new JFileChooser();
  private String defaultParser;
  
  public FileSequenceInput() 
  {
    super.setExceptionHandler(new FileSequenceParserExceptionHandler());
  }

  public void start()
  {
    super.start();
    
    // fetch the default parser from the config information. 
    defaultParser = getConfigProperties().getProperty( "default" );
    defaultParser = defaultParser.substring( 4, defaultParser.length() );
  }
  

  /**
   * Opens a file using a parser. This method was generated to allow
   * file parsing without the need for the open dialog - i.e., it will
   * make the passing of arguments to Cinema of the file name a lot
   * easier, or even possible.
   * @param file the file
   * @param parser the input parser
   * @param ident the identifier for the alignment
   * @return the sequence alignment
   */
  public SequenceAlignment openFile(File file, AlignmentInputParser parser, 
				    Identifier ident) 
    throws IOException
  {
    return parser.parse(ident, new FileReader(file), getExceptionHandler());
  }
  
  public SequenceAlignment openAlignment() 
  {
    SequenceAlignment alignment = null;
    
    /* (PENDING: JNS 14/06/00)
     *   x obtain list of parsers from ParserFactory
     *   o set potential file types
     *   x open file browser
     *   x get file
     *   x pass file + file type (& therefore parser) -> ParserFactory
     *   x return alignment
     */
    
    // obtain a list of the parsers from the factory
    String[] availableParsers = getAvailableParsers();

    // (PENDING: JNS 15/06/00) set the file types from the parsers
    //for (int i = 0; i < availableParsers.length; i++) {
    //  chooser.addChoosableFileFilter();
    //}

    // open the file chooser
    int selected = chooser.showOpenDialog(getFrame());
    // if open a file then pass it to the parse factory
    if (selected == JFileChooser.APPROVE_OPTION) {
      File file;
      if ( (file = chooser.getSelectedFile()) != null) 
        try {
	  // get alignment through parsing file
	  /* (PENDING: JNS 15/06/00) change "PIR" to something dynamic
	   * - will come with the writing of getting the parsers and
	   * getting the choosen parser
	   */
	  
	  // calculate the identifier based on the File name without extension
	  String fileName = file.getName();
	  int i = fileName.lastIndexOf( '.' );
	  String fileNameNoExtension = fileName;
	  if( i > 0 && i < fileName.length() - 1 ){
	    fileNameNoExtension = fileName.substring( 0, i );
	  }
	  fileNameNoExtension = fileNameNoExtension.toUpperCase();
          
	  // open the file and get the alignment
	  alignment = openFile(file, getParser( defaultParser ), 
			       new SimpleIdentifier(fileNameNoExtension, 
						    new FileSource(file)));
	  
        } catch (IOException e) {
	  if (e instanceof FileNotFoundException) {
	    if (Debug.debug)
	      Debug.message(this, "File Sequence Input: File not found");
	    JOptionPane message = new JOptionPane();
	    message.showMessageDialog
	      (getFrame(),
	       "The file doesn't exist! Please choose again",
	       "ERROR: File not found",
	       JOptionPane.ERROR_MESSAGE);
	    alignment = openAlignment();
	  } else if (Debug.debug) 
            Debug.both(this, "File Seuqence Input: An IOException was found",
                       e);
        }
    }
    
    if( alignment.getNumberSequences() == 0 ){
      JOptionPane message = new JOptionPane();
      message.showMessageDialog
        (getFrame(),
         "The file is either empty, or in an unsupported format. Please Choose again",
         "ERROR: Empty file, or unknown format",
         JOptionPane.ERROR_MESSAGE);
      alignment = openAlignment();
    }
    
    // return the alignment
    return alignment;
  }
  
  public String getVersion() 
  {
    return "$Id: FileSequenceInput.java,v 1.15 2002/04/20 14:58:56 lord Exp $";
  }
} // FileSequenceInput



/*
 * ChangeLog
 * $Log: FileSequenceInput.java,v $
 * Revision 1.15  2002/04/20 14:58:56  lord
 * Improved error handling
 *
 * Revision 1.14  2001/05/24 15:39:29  lord
 * Modified due to changes in parser factory
 *
 * Revision 1.13  2001/05/08 17:40:31  lord
 * Default parser now configurable
 *
 * Revision 1.12  2001/04/11 17:04:42  lord
 * Added License agreements to all code
 *
 * Revision 1.11  2001/04/11 16:31:20  lord
 * Changed default to seqret. Need to parameterise this class
 *
 * Revision 1.10  2001/01/27 16:54:03  lord
 * Removed status information which was not working anyway
 *
 * Revision 1.9  2000/12/05 15:54:37  lord
 * Import rationalisation
 *
 * Revision 1.8  2000/11/13 16:55:25  jns
 * o split of openAlignment into gui stuff and opening the file. This
 * will help later when doing command line loading which previously would
 * not have been possible. Not sure this is the best implementation, it
 * may be changed at a later stage to be incorperated in the interface.
 *
 * Revision 1.7  2000/10/31 15:51:55  lord
 * Added support for SequenceIdentifiers. Needs to be improved though.
 *
 * Revision 1.6  2000/09/11 16:23:41  lord
 * Put in new status message
 *
 * 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:23:24  jns
 * o reverting to standard exception handlers - no need for input and output
 * distinctions
 * o things specific to input parsers - name changes basically
 *
 * Revision 1.3  2000/08/01 14:55:18  jns
 * o AlignmentParser to AlignmentInputParser change of name so that output
 * parsers can be plugged in more logically.
 *
 * Revision 1.2  2000/06/30 09:55:09  jns
 * o added in 'file not found' handling
 * o some pendings still outstanding.
 *
 * 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.
 *
 */
