package toolbox.common.workflow.engine.scripting;

import javax.annotation.PostConstruct;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

import org.springframework.stereotype.Service;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class ScriptEngineFactory {
    
    private static ScriptEngineFactory self;
    
    private ThreadLocal<ScriptEngine> scriptEngine = new ThreadLocal<ScriptEngine>(){
        @Override
        protected ScriptEngine initialValue() {
          return new ScriptEngineManager().getEngineByName("nashorn");
        } 
    };
    
    private ThreadLocal<Boolean> initialized = new ThreadLocal<Boolean>(){
        @Override
        protected Boolean initialValue() {
          return false;
        } 
    };
    
    @PostConstruct
    public void initialized() {
        ScriptEngineFactory.self = this;
    }
      
    private ScriptEngine createEngineInternal() {
        ScriptEngine engine = scriptEngine.get();
        if(!initialized.get()){
            initialize(engine);
            initialized.set(true);
        }
        return engine;
    }
    
    public static ScriptEngine createEngine() {
        return self.createEngineInternal();
    }
    
    private void initialize(ScriptEngine engine) {
        log.info("initialing javascript execution engine");
        loadPreloadJavaObject(engine);
        //TODO inject other global java object such as logger, javascript code. business logic will bind local file variables in workflow service
    }
    
    private void loadPreloadJavaObject(ScriptEngine engine) {
        engine.put("logger", log);
    }
}

@@ -48,47 +48,8 @@
 g;%0A%0A
-import javax.annotation.PostConstruct;%0A
 impo
@@ -124,56 +124,8 @@
 r;%0A%0A
-import org.springframework.stereotype.Service;%0A%0A
 impo
@@ -166,17 +166,8 @@
 f4j%0A
-@Service%0A
 publ
@@ -225,51 +225,8 @@
 tic 
-ScriptEngineFactory self;%0A    %0A    private 
 Thre
@@ -467,16 +467,23 @@
 private 
+static 
 ThreadLo
@@ -653,120 +653,21 @@
     
-@PostConstruct%0A    public void initialized() %7B%0A        ScriptEngineFactory.self = this;%0A    %7D%0A      %0A    private
+public static
  Scr
@@ -688,24 +688,16 @@
 teEngine
-Internal
 () %7B%0A   
@@ -895,117 +895,21 @@
    p
-ublic static ScriptEngine createEngine() %7B%0A        return self.createEngineInternal();%0A    %7D%0A    %0A    private
+rivate static
  voi
@@ -1051,160 +1051,14 @@
     
+%7D%0A
     
-//TODO inject other global java object such as logger, javascript code. business logic will bind local file variables in workflow service%0A    %7D%0A    
 %0A   
@@ -1065,16 +1065,23 @@
  private
+ static
  void lo
@@ -1164,10 +1164,15 @@
 ;%0A    %7D%0A
+    %0A
 %7D%0A

optimize js engine creation