package commons.cmd;
import basics.filesystem.file.FileUtl;
import basics.filesystem.file.LineReader;
import basics.unexpected.Problem;
import basics.utl.Empty;
import commons.application.GLOBAL;
import commons.application.Application;
import commons.application.core.Command;
import commons.utl.CtxUtl;
public class call extends Command
{

private static final String ARGS = "ARGS: <script>, suffix .script is automatically added.";

public void process () throws Problem
{
   try
   {
      String scriptName = ctx.consume(GLOBAL.CTX_ENVKEY_ARG0, "").trim();
      if (Empty.is(scriptName))
         throw new Problem("Missing arg. " + ARGS);
      if (!scriptName.toLowerCase().endsWith(GLOBAL.VAL_SCRIPT_SUFFIX))
         scriptName = scriptName + GLOBAL.VAL_SCRIPT_SUFFIX;
      String path = FileUtl.concat(CtxUtl.scriptSpace(ctx).getAbsolutePath(), scriptName);
      LineReader reader = new LineReader(path);
      if (!reader.open())
         throw new Problem("Can't find script " + path);
      while (!Application.engine().isStopped() && reader.hasLine())
      {
         String cmdLine = reader.nextLine();
         if (!Empty.is(cmdLine))
         {
            Application.engine().call(cmdLine, ctx, null, null);
            Application.ui().print(ctx);
         }
      }
      reader.close();
   }
   catch (Throwable e)
   {
      e.printStackTrace();
      throw new Problem(e.getMessage());
   }
}

public void signContract ()
{}

public String description ()
{
   return implName()
      + " runs a batch script. Script will be performed until target value is reached if a controller is set that registers at least one strategy."
      + ARGS;
}
}
