package basics.testing;

import java.io.File;
import basics.application.Args;
import basics.unexpected.ProblemHandler;
import basics.utl.FormatterUtl;

public abstract class Function extends Test implements ProblemHandler
{
static boolean success = false;

public static void main(String [] args)
{
   try
   {
      Function.start(args);
   }
   catch(Throwable t)
   {
      printout("Starting function test failed. " + t.getMessage());
   }
}

public abstract boolean setup(Args args);

public abstract boolean testfunction();

public abstract boolean teardown();

public static void start(String [] _args)
{
   Args args = new Args(_args);
   if(args.getSwitch("abort", false))
      abortOnError = true;
   File logfile = new File(LOGFILE);
   if(logfile.exists())
      try
      {
         logfile.delete();
      }
      catch(Exception e)
      {
      }
   String testclass = args.getFirstArgument("");
   try
   {
      redirectOutput();
      Class<?> c = Class.forName(testclass);
      Function tf = (Function)c.newInstance();
      boolean success = false;
      long t0 = System.currentTimeMillis();
      if(tf.setup(args))
         if(tf.testfunction())
            if(tf.teardown())
               success = true;
      long t1 = System.currentTimeMillis();
      if(success)
         printout(testclass + " " + FormatterUtl.timestring(t1 - t0) + " " + memory.toString());
      else
         printout("FAILED: " + testclass); // + " " + SU.timestring(t1 - t0) + " " + memory.toString());
      endRedirectOutput();
   }
   catch(Throwable t)
   {
      t.printStackTrace();
      printout("Starting function test '" + testclass + "' failed. ");
      handleAsFailure(t);
   }
}

/**
 * Call back from OM notifies a problem.
 */
public void handleProblem(Throwable t)
{
   success = false;
   printout(t.getMessage());
   System.out.println("------------------- P R O B L E M -------------------");
   System.out.println(t.getMessage());
   System.out.println("-----------------------------------------------------");
   System.out.println("Exception stack:");
   t.printStackTrace();
   System.out.println("-----------------------------------------------------");
}

public static void unittest()
{
}
}
