package at.oefai.aaa.agent.jam;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import at.oefai.aaa.agent.jam.types.Binding;
import at.oefai.aaa.agent.jam.types.ExpList;
import at.oefai.aaa.agent.jam.types.Expression;

/**
 * A built-in JAM primitive action for loading files for parsing by the JAM parser.
 *
 * @author Marc Huber
 * @author Jaeho Lee
 */
class LoadAction extends AbstractAction implements Serializable {

    private final ExpList args;
    private final Interpreter interpreter;

    /**  */
    LoadAction(final ExpList pExpList, final Interpreter pInterpreter) {
        this.args = pExpList;
        this.interpreter = pInterpreter;
    }

    // Member functions

    public boolean isExecutableAction() {
        return true;
    }

    public Result execute(final Binding b, final Goal currentGoal) {
        List<String> filenames = new ArrayList<String>();
        for (Expression e : this.args) {
            filenames.add(e.eval(b).getString());
        }
        this.interpreter.getLog().info("LoadAction: loading \"" + filenames + "\"");
        try {
            this.interpreter.parseFiles(filenames);
            return Result.SUCCEEDED;
        } catch (IOException e) {
            this.interpreter.getLog().warning("IOException loading \"" + filenames + "\"", e);
            return Result.FAILED;
        } catch (ParseException e) {
            this.interpreter.getLog().warning("ParseException parsing \"" + filenames + "\"", e);
            return Result.FAILED;
        }
    }

    /**  */
    public String formattedString(final Binding b) {
        return "LOAD: " + this.args.formattedString(b);
    }

    public String getName() {
        return "LOAD";
    }
}
