/*
 *  @(#)StateIteratorTask.java
 *
 * Copyright (C) 2002-2003 Matt Albrecht
 * groboclown@users.sourceforge.net
 * http://groboutils.sourceforge.net
 *
 *  Part of the GroboUtils package at:
 *  http://groboutils.sourceforge.net
 *
 *  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.
 */
package net.sourceforge.groboutils.mbtf.v1.ant;

import org.apache.tools.ant.Project;
import org.apache.tools.ant.ProjectHelper;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.TaskAdapter;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.types.Reference;
import org.apache.tools.ant.types.DataType;
import org.apache.tools.ant.taskdefs.Definer;

import java.util.Vector;
import java.util.Enumeration;

import net.sourceforge.groboutils.mbtf.v1.IValidate;
import net.sourceforge.groboutils.mbtf.v1.ISystemFactory;
import net.sourceforge.groboutils.mbtf.v1.ISystem;
import net.sourceforge.groboutils.mbtf.v1.IErrors;
import net.sourceforge.groboutils.mbtf.v1.ITransition;
import net.sourceforge.groboutils.mbtf.v1.IState;
import net.sourceforge.groboutils.mbtf.v1.IPathGenerator;
import net.sourceforge.groboutils.mbtf.v1.IPath;
import net.sourceforge.groboutils.mbtf.v1.IPathParser;
import net.sourceforge.groboutils.mbtf.v1.TestHaltRuntimeException;

import net.sourceforge.groboutils.mbtf.v1.engine.PathParserImpl;
import net.sourceforge.groboutils.mbtf.v1.engine.BreadthPathGenerator;

import net.sourceforge.groboutils.mbtf.v1.assembler.AsmblState;
import net.sourceforge.groboutils.mbtf.v1.assembler.AsmblStateSet;
import net.sourceforge.groboutils.mbtf.v1.assembler.AsmblTransition;
import net.sourceforge.groboutils.mbtf.v1.assembler.AsmblTransitionSet;
import net.sourceforge.groboutils.mbtf.v1.assembler.Assembler;


/**
 * An ant datatype encapsulating the IState instance.  This includes an
 * <tt>execute()</tt> method to allow for this to be defined in a
 * &lt;typedef&gt; declaration, rather than inside a target as a
 * &lt;datatype&gt; declaration.
 *
 * @author     Matt Albrecht <a href="mailto:groboclown@users.sourceforge.net">groboclown@users.sourceforge.net</a>
 * @version    $Date: 2003/02/10 22:52:25 $
 * @since      June 13, 2002
 */
public class StateIteratorTask extends Task
{
    public static final String DEFAULT_ANT_NAME = "mbtf.stateiterator";
    
    
    private Vector transitions = new Vector();
    private Vector states = new Vector();
    private Reference systemFactory;
    private int maxDepth = 4;
    
    
    public void setSystemFactoryRef( Reference ref )
    {
        this.systemFactory = ref;
    }
    
    
    public ISystemFactory getSystemFactory()
            throws BuildException
    {
        ISystemFactory sys = null;
        if (this.systemFactory != null)
        {
            Object o = this.systemFactory.getReferencedObject( project );
            if (o != null)
            {
                if (o instanceof TaskAdapter)
                {
                    o = ((TaskAdapter)o).getProxy();
                }
                if (!( o instanceof ISystemFactory ))
                {
                    throw new BuildException(
                        "referenced object not of type ISystemFactory",
                        location );
                }
                sys = (ISystemFactory)o;
            }
        }
        return sys;
    }
    
    
    public void setMaxDepth( int depth )
            throws BuildException
    {
        if (depth <= 0)
        {
            throw new BuildException("invalid value for maximum depth: "+
                depth, location );
        }
        this.maxDepth = depth;
    }
    
    
    public int getMaxDepth()
    {
        return this.maxDepth;
    }
    
    
    public void addState( StateType state )
    {
        if (state != null)
        {
            this.states.addElement( state );
        }
    }
    
    
    public AsmblStateSet getStates()
            throws BuildException
    {
        Enumeration enum = this.states.elements();
        AsmblStateSet ass = new AsmblStateSet();
        while (enum.hasMoreElements())
        {
            ass.addState( ((StateType)enum.nextElement()).createState() );
        }
        
        return ass;
    }
    
    
    public void addTransition( TransitionType trans )
    {
        if (trans != null)
        {
            this.transitions.addElement( trans );
        }
    }
    
    
    public AsmblTransitionSet getTransitions()
            throws BuildException
    {
        Enumeration enum = this.transitions.elements();
        AsmblTransitionSet ats = new AsmblTransitionSet();
        while (enum.hasMoreElements())
        {
            ats.addTransition( ((TransitionType)enum.nextElement()).
                createTransition() );
        }
        return ats;
    }
    
    
    public void execute()
            throws BuildException
    {
        IPathGenerator gen = createPathGenerator();
        IPathParser parser = createPathParser();
        ISystemFactory sysFactory = getSystemFactory();
        
        try
        {
            IPath path = gen.getNextPath();
            while (path.getDepth() <= getMaxDepth())
            {
                ISystem sys = sysFactory.createSystem();
                if (sys == null)
                {
                    throw new BuildException(
                        "System factory returned a null factory.", location );
                }
                IErrors err = parser.parsePath( path, sys );
            }
        }
        catch (TestHaltRuntimeException thre)
        {
            throw new BuildException( thre.getMessage(), thre, location );
        }
    }
    
    
    public IPathGenerator createPathGenerator()
            throws BuildException
    {
        try
        {
            Assembler asm = new Assembler( getTransitions(), getStates() );
        
            IState startStates[] = asm.getStartStates();
            IState finalStates[] = asm.getFinalStates();
            
            return new BreadthPathGenerator( startStates, finalStates );
        }
        catch (Exception e)
        {
            throw new BuildException( e.getMessage(), e );
        }
    }
    
    
    protected IPathParser createPathParser()
            throws BuildException
    {
        return new PathParserImpl();
    }
    
    
    protected void processErrors( IErrors err )
    {
        log( err.toString(), Project.MSG_WARN );
    }
}

