/**
 * @license
 * Copyright 2017 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

package foam.nanos.script;

import foam.core.*;
import foam.dao.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import foam.nanos.pool.FixedThreadPool;

public class ScriptRunnerDAO
  extends ProxyDAO
  {
  final public static int DEFAULT_WAIT_TIME = 2000;

  public ScriptRunnerDAO(DAO delegate)
  {
    super();
    setDelegate(delegate);
  }

  public FObject put_(final X x, FObject obj)
  {
    Script script = (Script) obj;

    if ( script.getStatus() == ScriptStatus.SCHEDULED ) {
      this.runScript(x, script);
    }

    return getDelegate().put_(x, obj);
  }

  private void runScript(final X x, Script script)
  {
    long estimatedTime = this.estimateWaitTime(script);
    final CountDownLatch latch = new CountDownLatch(1);

    try {
      ((FixedThreadPool) x.get("threadPool")).submit(x, new ContextAgent(){

        @Override
        public void execute(X y) {
          try {
            script.setStatus(ScriptStatus.RUNNING);
            getDelegate().put_(x, script);
            script.runScript(x);
            script.setStatus(ScriptStatus.UNSCHEDULED);
          } catch(Throwable t) {
            script.setStatus(ScriptStatus.ERROR);
            t.printStackTrace();
          }
          // save the state
          getDelegate().put_(x, script);

          latch.countDown();
        }
      });

      latch.await(estimatedTime, TimeUnit.MILLISECONDS);

    } catch(InterruptedException e) {
      e.printStackTrace();
    }
  }

  private long estimateWaitTime(Script script)
  {
      if ( script.getLastRun() == null || DEFAULT_WAIT_TIME > script.getLastDuration() * 2 )
        return DEFAULT_WAIT_TIME;
      //  1 ms so it returns right away
      return 1;
  }
}

@@ -355,20 +355,18 @@
 roxyDAO%0A
-  
 %7B%0A
+
   final 
@@ -448,18 +448,16 @@
 elegate)
-%0A 
  %7B%0A    s
@@ -541,18 +541,16 @@
 ect obj)
-%0A 
  %7B%0A    S
@@ -725,21 +725,23 @@
  %7D%0A%0A  pr
-ivate
+otected
  void ru
@@ -769,26 +769,24 @@
 ript script)
-%0A 
  %7B%0A    long 
@@ -977,11 +977,11 @@
 nt()
+ 
 %7B%0A
-%0A
     
@@ -1619,13 +1619,15 @@
   pr
-ivate
+otected
  lon
@@ -1659,18 +1659,16 @@
  script)
-%0A 
  %7B%0A     
@@ -1664,28 +1664,30 @@
 pt) %7B%0A      
-if (
+return
  script.getL
@@ -1755,17 +1755,17 @@
 n() * 2 
-)
+?
 %0A       
@@ -1765,23 +1765,16 @@
         
-return 
 DEFAULT_
@@ -1782,23 +1782,30 @@
 AIT_TIME
-;%0A
+ :%0A  
      
+ 1 ;
  //  1 m
@@ -1835,23 +1835,8 @@
 way%0A
-      return 1;
 %0A  %7D

Fix formatting.