/*******************************************************************************
* Copyright (c)                                                                *
*           2005   Tristan Allwood,                                            *
*           2005   Daniel Burke,                                               *
*           2005   Marc Hull,                                                  *
*           2005   Ekaterina Itskova,                                          *
*           2005   Steve Zymler                                                *
*                                                                              *
* Permission is hereby granted, free of charge, to any person obtaining a      *
* copy of this software and associated documentation files (the                *
* "Software"), to deal in the Software without restriction, including          *
* without limitation the rights to use, copy, modify, merge, publish,          *
* distribute, sublicense, and/or sell copies of the Software, and to           *
* permit persons to whom the Software is furnished to do so, subject to        *
* the following conditions:                                                    *
*                                                                              *
* The above copyright notice and this permission notice shall be included      *
* in all copies or substantial portions of the Software.                       *
*                                                                              *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS      *
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF                   *
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.       *
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY         *
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,         *
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE            *
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                       *
*******************************************************************************/
/*
 * Created on 21-Oct-2004
 *
 */
package uk.ac.ic.doc.kevlar.core.programs.fileUtils;

import java.io.File;
import java.util.Map;

import uk.ac.ic.doc.kevlar.api.programs.arguments.IArgumentInstance;
import uk.ac.ic.doc.kevlar.api.programs.arguments.ISetArgumentValue;
import uk.ac.ic.doc.kevlar.core.types.textType.IFilenameType;
import uk.ac.ic.doc.kevlar.publicInterfaces.AbstractProgram;
import uk.ac.ic.doc.kevlar.publicInterfaces.ICloseEventListener;
import uk.ac.ic.doc.kevlar.publicInterfaces.IInputPipe;
import uk.ac.ic.doc.kevlar.publicInterfaces.IOutputPipe;
import uk.ac.ic.doc.kevlar.publicInterfaces.IPipeEnd;

/**
 * @author Tristan
 * 
 */
public class MakeDirectory extends AbstractProgram {

    IOutputPipe succ;

    IOutputPipe fail;

    public void run(IArgumentInstance args, Map<String, IInputPipe> inputs,
            Map<String, IOutputPipe> outputs) {

        ISetArgumentValue val = (ISetArgumentValue) args.getAssigmentsMap()
                .get("Directories-Input");

        if (val != null && val.getValue().equals("On")) {
            // pipes of dirs
            
            IInputPipe in = inputs.get("Directories");
            
            fail = outputs.get("Error");
            succ = outputs.get("Made-Directories");
            
            /* a minor optimisation */
            succ.addCloseEventListener(new ICloseEventListener() {
                public void pipeClosed(IPipeEnd source) {
                    succ = null;
                }
            });

            fail.addCloseEventListener(new ICloseEventListener() {
                public void pipeClosed(IPipeEnd source) {
                    fail = null;
                }
            });

            // nowt to do
            if( in == null ) {
                exit(0);
                return;
            }
            
            while( true ) {
                try {
                handlePipeDir( (IFilenameType) in.read() );
                } catch ( IllegalStateException ise ) {
                    exit(0);
                    //its ok, we're done
                } catch (InterruptedException ie ) {
                    ie.printStackTrace();
                    exit(1);
                }
            }
            
            
        } else if (val != null && val.getValue().equals("Off")) {
            // just create a single dir

            String dirName = args.getText("Directory");
            if (dirName == null) {
                exit(1);
                return;
            }

            File f = new File(dirName);

            exit(handleDirectory(f) ? 0 : 1);

        } else {
            exit(1);
        }

    }

    private void handlePipeDir(IFilenameType ift) {

        IOutputPipe iop = handleDirectory(ift.getFile()) ? succ : fail;

        try {
            if (iop != null) {
                iop.write(ift);
            }
        } catch (IllegalStateException ise) {
            /* ignore it */
        }
    }

    /**
     * @param f
     *            File representing a directory to be created.
     * @return true iff the directory was created.
     */
    private boolean handleDirectory(File f) {

        try {
            return f.mkdir();
        } catch (SecurityException se) {
            return false;
        }

    }

}
