package jp.vmi.selenium.selenese;

import org.apache.commons.io.FilenameUtils;

import jp.vmi.selenium.selenese.result.Error;
import jp.vmi.selenium.selenese.result.Result;
import jp.vmi.selenium.selenese.utils.PathUtils;
import jp.vmi.selenium.selenese.utils.StopWatch;

/**
 *
 */
public abstract class ErrorSource implements Selenese {

    private String filename;
    private String baseName;
    private InvalidSeleneseException e;

    private final StopWatch stopWatch = new StopWatch();

    /**
     * Initialize.
     *
     * @param filename Selenese script file.
     * @param e InvalidSeleneseException or null.
     * @return this.
     */
    public ErrorSource initialize(String filename, InvalidSeleneseException e) {
        this.filename = PathUtils.normalize(filename);
        this.baseName = FilenameUtils.getBaseName(filename);
        this.e = e;
        return this;
    }

    /**
     * Is error object?
     *
     * @return true.
     */
    @Override
    public boolean isError() {
        return true;
    }

    @Override
    public String getName() {
        return FilenameUtils.getBaseName(filename);
    }

    @Override
    public String getId() {
        return getName();
    }

    /**
     * Get filename.
     *
     * @return filename.
     */
    public String getFilename() {
        return filename;
    }

    @Override
    public String getBaseName() {
        return baseName;
    }

    @Override
    public StopWatch getStopWatch() {
        return stopWatch;
    }

    @Override
    public Result execute(Selenese parent, Context context) throws InvalidSeleneseException {
        throw e;
    }

    /**
     * Get result.
     *
     * @return result.
     */
    @Override
    public Result getResult() {
        return new Error(e);
    }

    @Override
    public String toString() {
        // remove suffix generated by Guice.
        String name = getClass().getSimpleName().replaceFirst("\\$\\$.*$", "");
        return String.format("%s[%s] %s", name, filename, e.getMessage());
    }
}
