
/*
 * class: Transformer
 *
 * Version $Id: Transformer.txt,v 1.1 2003/08/01 20:01:36 atlee Exp $
 *
 * Date: May 20 2003
 *
 * (c) 2003 IceCube Collaboration
 */

package icecube.testdaq.generator;

import icecube.testdaq.domrawio.LeCroy2DomRawSpecs;
import icecube.testdaq.domrawio.OutputWriteException;
import icecube.testdaq.domrawio.OutputWriter;
import icecube.testdaq.domrawio.TransformerFailure;
import icecube.testdaq.lecroyio.FileListReader;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import java.io.File;
import java.io.FileOutputStream;
import java.util.LinkedList;

/**
 * This class ...does what?
 *
 * @version $Id: Transformer.txt,v 1.1 2003/08/01 20:01:36 atlee Exp $
 * @author mka
 */
public class Transformer {

    // public static final member data
    public static LeCroy2DomRawSpecs lc2DrSpecs;
    LinkedList inputFileList;

    // protected static final member data

    // static final member data

    // private static final member data

    // private static member data

    // private instance member data

    // constructors

    /**
     * Create an instance of this class.
     * Default constructor is declared, but private, to stop accidental
     * creation of an instance of the class.
     */
    private Transformer() {
    }

    public Transformer( LeCroy2DomRawSpecs lc2DrSpecs )
            throws TransformerFailure, OutputWriteException {

        this.lc2DrSpecs = lc2DrSpecs;
    }

    // instance member method (alphabetic)
    /**
     * This is the method that makes use of all tranformation parameters, once
     * all the entries have been validated.
     *
     * The sequence is:
     * - Take the list of input files and use it with the LeCroyFileList parser
     * - Prepare the output according to the output parameters
     * - get the list of doms and pass them to a DOM looper
     * - get the overall looping to start: for each DOM in the list, read in
     *   pulse specifications, construct the pulse, create the pulse as it looks
     *   in each device together with filling all other necessary information
     *   and write the output to output.
     */
    public void transform() throws TransformerFailure, OutputWriteException {

        // ATTENTION THIS IS JUST FOR NOW! WE NEED A LIST IN THE XML FILE.
        // ATTENTION THIS IS JUST FOR NOW! WE NEED A LIST IN THE XML FILE.
        // ATTENTION THIS IS JUST FOR NOW! WE NEED A LIST IN THE XML FILE.
        // ATTENTION THIS IS JUST FOR NOW! WE NEED A LIST IN THE XML FILE.
        // ATTENTION THIS IS JUST FOR NOW! WE NEED A LIST IN THE XML FILE.
        // ATTENTION THIS IS JUST FOR NOW! WE NEED A LIST IN THE XML FILE.
  //      inputFileList = new LinkedList();
  //      inputFileList.add( lc2DrSpecs.getLeCroy2DomRawSpec().getInputFileList() );
  //      inputFileList.add( lc2DrSpecs.getLeCroy2DomRawSpec().getInputFile() );
  //      inputFileList.add( lc2DrSpecs.getLeCroy2DomRawSpec().getInputFile() );

        // Check the input settings from the transformation xml file:
        testInputSettings( inputFileList );

        // Check the input settings from the transformation xml file:
  //      testOutputSettings( lc2DrSpecs.getLeCroy2DomRawSpec().getOutputDir() );

        // As input is available and the output directory is prepared, we can
        // start with making a copy of the xml file into the outputdirectory:
        JAXBContext jc = null;
        try {
            jc = JAXBContext.newInstance(
                            "icecube.testdaq.domrawio" );
            FileOutputStream outputFile = null;
  //          try {
   //             outputFile = new FileOutputStream
  //                      ( lc2DrSpecs.getLeCroy2DomRawSpec().getOutputDir() +
  //                      "/lc2DrSpecs.xml");
  //          } catch ( FileNotFoundException e ) {
   //             e.printStackTrace();
 //           }
            Marshaller m = jc.createMarshaller();
            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, outputFile);
            m.marshal( (Object) lc2DrSpecs,
                    outputFile );
        } catch ( JAXBException e ) {
            e.printStackTrace();  //To change body of catch statement use Options | File Templates.
        }

        // Now create the file list reader:
        FileListReader fileListReader = new icecube.testdaq.lecroyio.
                FileListReader( inputFileList );

        // put all the settings together and prepare the output directory

        // create a domraw writer for the output into file in the output
        // directory:
        // JUST FOR NOW: LATER -- REPLACE WITH ....getOutputFileSpecs()
        // JUST FOR NOW: LATER -- REPLACE WITH ....getOutputFileSpecs()
        // JUST FOR NOW: LATER -- REPLACE WITH ....getOutputFileSpecs()
        // JUST FOR NOW: LATER -- REPLACE WITH ....getOutputFileSpecs()
        // JUST FOR NOW: LATER -- REPLACE WITH ....getOutputFileSpecs()
        // JUST FOR NOW: LATER -- REPLACE WITH ....getOutputFileSpecs()
        // JUST FOR NOW: LATER -- REPLACE WITH ....getOutputFileSpecs()
        // JUST FOR NOW: LATER -- REPLACE WITH ....getOutputFileSpecs()
        // JUST FOR NOW: LATER -- REPLACE WITH ....getOutputFileSpecs()
 //       OutputWriter outputWriter = new OutputWriter(
 //               lc2DrSpecs.getLeCroy2DomRawSpec().getOutputDir(),
 //               lc2DrSpecs.getLeCroy2DomRawSpec().getOutputBaseName(),
 //               lc2DrSpecs.getLeCroy2DomRawSpec().getNumRecPFilePDom(),
 //               lc2DrSpecs.getLeCroy2DomRawSpec().getNumOfFiles() );
    }

    /**
     * This method tests whether the output directory can be erased from any
     * files that may lie around there -- any other directories are not touched.
     * If this is not the case, an exception is thrown, causing the
     * transformation to stop / exit.
     *
     * @param outputDir the directory where the output is going to be written
     */
    private void testOutputSettings( String outputDir )
            throws OutputWriteException {

        File file;
        file = new File( outputDir );
        // Check that the outputDir exists:
        if ( file.exists() == false ) {

            if ( file.mkdirs() == false ) {

                throw new OutputWriteException( this.getClass().getName() +
                        ": Could not create " + outputDir + " on your system.");
            }
        }

        // Check that the outputDir is a directory at all:
        if ( new File( outputDir ).isDirectory() == false ) {

            throw new OutputWriteException( this.getClass().getName() +
                    ": " + outputDir + " is not a directory." );
        }

        // Check that the output directory can be written to
        if ( new File( outputDir ).canWrite() == false ) {

            throw new OutputWriteException( this.getClass().getName() +
                    ": can not write to directory " + outputDir );
        }

        // Check now that all files in the outputdirectory can be erased:
        File[] filesInOutputDir = new File( outputDir ).listFiles();
        for ( int iFile = 0; iFile < filesInOutputDir.length; iFile++) {

            if ( filesInOutputDir[iFile].canWrite() == false ){

                throw new OutputWriteException( this.getClass().getName() +
                        ": can not delete file " + filesInOutputDir[iFile] +
                        " in directory " + outputDir );
            }
        }
    }

    /**
     * As a first step for the transformation check that the input files listed
     * in the xml file are accessible. Keep only those that are accessible.
     * If the list is empty afterwards throw an exception, causing the program
     * to stop / exit.
     *
     * @param inputFileList list of input files, read in from the xml file
     * @throws TransformerFailure
     */
    private void testInputSettings( LinkedList inputFileList )
            throws TransformerFailure {

        for ( int iMember = 0; iMember < inputFileList.size(); iMember++ ) {

            Object object = inputFileList.get( iMember );
            String fileName = (String)object;

            if ( new File( fileName ).canRead() == false ) {

                inputFileList.remove( fileName );
            }
        }

        if ( inputFileList.size() == 0 )
            throw ( new TransformerFailure(
                    this.getClass().toString() + " no single input file is " +
                    "readable " ) );

    }

    // static member methods (alphabetic)

    // Description of this object.
    // public String toString() {}

    // public static void main(String args[]) {}
}
