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

package foam.nanos.boot;

import foam.core.*;
import foam.nanos.*;
import foam.nanos.logger.Logger;
import foam.nanos.pm.PM;

public class NSpecFactory
  implements XFactory
{
  NSpec   spec_;
  ProxyX  x_;
  boolean isCreating_ = false;

  public NSpecFactory(ProxyX x, NSpec spec) {
    x_    = x;
    spec_ = spec;
  }

  public Object create(X x) {
    // Avoid infinite recursions when creating services
    if ( isCreating_ ) {
      if ( ! "startupLogger".equals(spec_.getName()) ) {
        Logger startupLogger = (Logger) x.get("startupLogger");
        if ( startupLogger != null ) startupLogger.warning("Recursive Service Factory", spec_.getName());
      }

      return null;
    }

    isCreating_ = true;

    Object ns     = null;
    PM     pm     = new PM(this.getClass(), spec_ == null ? "-" : spec_.getName());
    Logger startupLogger = (Logger) x.get("startupLogger");

    try {
      if ( startupLogger != null ) startupLogger.info("Creating Service", spec_.getName());
      ns = spec_.createService(x_.getX());
      if ( startupLogger != null ) startupLogger.info("Created Service", spec_.getName());

      if ( ns instanceof ContextAware ) ((ContextAware) ns).setX(x_.getX());
      if ( ns instanceof NanoService  ) ((NanoService)  ns).start();
    } catch (Throwable t) {
      if ( startupLogger != null ) startupLogger.error("Error Creating Service", spec_.getName(), t);
    } finally {
      pm.log(x_.getX());
      isCreating_ = false;
    }

    return ns;
  }
}

@@ -565,24 +565,17 @@
 if ( ! %22
-startupL
+l
 ogger%22.e
@@ -612,32 +612,25 @@
      Logger 
-startupL
+l
 ogger = (Log
@@ -637,32 +637,25 @@
 ger) x.get(%22
-startupL
+l
 ogger%22);%0A   
@@ -660,32 +660,25 @@
        if ( 
-startupL
+l
 ogger != nul
@@ -677,32 +677,25 @@
 r != null ) 
-startupL
+l
 ogger.warnin
@@ -924,24 +924,17 @@
  Logger 
-startupL
+l
 ogger = 
@@ -949,24 +949,17 @@
  x.get(%22
-startupL
+l
 ogger%22);
@@ -977,32 +977,25 @@
 %0A      if ( 
-startupL
+l
 ogger != nul
@@ -994,32 +994,25 @@
 r != null ) 
-startupL
+l
 ogger.info(%22
@@ -1098,32 +1098,25 @@
 %0A      if ( 
-startupL
+l
 ogger != nul
@@ -1115,32 +1115,25 @@
 r != null ) 
-startupL
+l
 ogger.info(%22
@@ -1354,24 +1354,17 @@
    if ( 
-startupL
+l
 ogger !=
@@ -1375,16 +1375,9 @@
 l ) 
-startupL
+l
 ogge
@@ -1526,9 +1526,8 @@
 s;%0A  %7D%0A%7D
-%0A

revert changes and call logger from NspecFactory