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

package foam.nanos.dig;

import foam.core.Detachable;
import foam.core.FObject;
import foam.core.X;
import foam.dao.AbstractSink;
import foam.dao.DAO;
import foam.dao.JDAO;
import foam.dao.ProxyDAO;
import foam.nanos.auth.User;
import foam.util.Auth;

/** Execute DUGs on startup or when first put(). Set DUG.owner to creator. **/
public class DUGDAO
  extends ProxyDAO
{
  public DUGDAO(X x) {
    this(x, new JDAO(x, DUG.getOwnClassInfo(), "dugs"));
  }

  public DUGDAO(X x, DAO delegate) {
    super(x, delegate);
    delegate.select(new AbstractSink() {
      @Override
      public void put(Object obj, Detachable sub) {
        ((DUG) obj).execute(Auth.sudo(x, ((DUG) obj).getOwner()));
      }
    });
  }

  @Override
  public FObject put_(X x, FObject obj) {
    User user = (User) x.get("user");
    ((DUG) obj).setOwner(user.getId());
    ((DUG) obj).execute(x);
    return super.put_(x, obj);
  }
}

@@ -345,16 +345,49 @@
 h.User;%0A
+import foam.nanos.logger.Logger;%0A
 import f
@@ -401,16 +401,16 @@
 l.Auth;%0A
-
 %0A/** Exe
@@ -668,16 +668,17 @@
 egate);%0A
+%0A
     dele
@@ -790,42 +790,22 @@
     
-((DUG) obj).execute(Auth.sudo
+executeDUG
 (x, 
-(
 (DUG
@@ -814,21 +814,8 @@
 obj)
-.getOwner()))
 ;%0A  
@@ -929,27 +929,47 @@
 %22);%0A    
-((DUG) obj)
+DUG  dug  = (DUG) obj;%0A%0A    dug
 .setOwne
@@ -993,32 +993,29 @@
     
-((DUG) obj).execute(x
+executeDUG(x, dug
 );%0A
+%0A
     
@@ -1044,11 +1044,274 @@
 bj);%0A  %7D
+%0A%0A  protected void executeDUG(X x, DUG dug) %7B%0A    try %7B%0A      dug.execute(Auth.sudo(x, dug.getOwner()));%0A    %7D catch (Throwable t) %7B%0A      Logger logger = (Logger) x.get(%22logger%22);%0A      logger.error(DUGDAO.class, %22Error executing DUG%22, dug.getId(), t);%0A    %7D%0A  %7D
 %0A%7D%0A

Add error logging to DUGDAO.