/*
 * This file is part of the DistSim distributed simulation framework (wrapper)
 * Copyright (C) 2007 Ulf Hermann
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
package brn.distsim.wrapper;

import java.io.File;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.rmi.RemoteException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

public class Simulation {

  private static final long serialVersionUID = 4941091157101209595L;

  private static final int REPEAT_SIMULATION = 42;

  private String commandLine;

  private boolean success = true;

  private Process simulation;

  private DBConnector db;

  private int id;

  private String studyName;

  private String studyVersion;

  public Simulation(ResultSet template, ResultSet params, Properties p,
      int id, DBConnector db) throws RemoteException {
    try {
      this.db = db;
      this.id = id;
      p.put("simulationId", "" + id);
      if (template.next()) {
        studyName = template.getString("name");
        studyVersion = template.getString("version");
        commandLine = template.getString("command");
        while (params.next()) {
          String name = params.getString("name");
          String val = params.getString("value");
          commandLine = commandLine.replaceAll("\\$" + name + "\\$",
              val);
          p.put(name, val);
        }
      }

    } catch (SQLException e) {
      // TODO Automatisch erstellter Catch-Block
      e.printStackTrace();
    }
  }

  public boolean execute(Properties input, File workingDir) throws SQLException {
    try {
      while (true) {

        if (System.getProperty("os.name").toLowerCase().contains("windows"))
          if (null != commandLine)
            commandLine = commandLine.replaceAll("ant", "ant.bat");

        System.out.println("new simulation " + id + ": " + commandLine);
        if (null == commandLine)
          return false;

        simulation = Runtime.getRuntime().exec(commandLine, null, workingDir);

        input.store(simulation.getOutputStream(), null);
        simulation.getOutputStream().close();
        try {
          db.writeStdOutToDB(simulation.getInputStream());
          db.writeStdErrToDB(simulation.getErrorStream());
        } catch (InterruptedIOException e) {
          // pass ...
        }
        int returnValue;
        try {
          returnValue = simulation.waitFor();
        } catch (InterruptedException e) {
          returnValue = 1;
        }
        if (returnValue == REPEAT_SIMULATION) {
          System.out.println("repeating simulation");
          db.jobRepeated();
        } else if (returnValue == 0){
          System.out.println("simulation successful");
          break;
        } else {
          success = false;
          System.out.println("simulation failed. return value: " + returnValue);
          break;
        }
      }
    } catch (IOException e) {
      e.printStackTrace();
      success = false;
    } catch (IllegalArgumentException e) {
      e.printStackTrace();
      success = false;
    }
    return success;
  }

  public void destroy() {
    success = false;
    if (simulation != null)
      simulation.destroy();
  }

  public String toString() {
    return "Simulation(id="+this.id+",db="+db.toString()+")";
  }

  /**
   * @return the studyName
   */
  public String getStudyName() {
    return studyName;
  }

  /**
   * @return the studyVersion
   */
  public String getStudyVersion() {
    return studyVersion;
  }
}
