package foam.nanos.notification;

import foam.core.Detachable;
import foam.core.FObject;
import foam.core.X;
import foam.dao.AbstractSink;
import foam.dao.DAO;
import foam.dao.ProxyDAO;
import foam.nanos.auth.User;
import foam.util.SafetyUtil;
import static foam.mlang.MLang.EQ;

public class SendNotificationDAO
  extends ProxyDAO
{

  public SendNotificationDAO(X x, DAO delegate) {
    setX(x);
    setDelegate(delegate);
  }

  @Override
  public FObject put_(X x, FObject obj) {
    DAO userDAO = (DAO) x.get("localUserDAO");
    Notification notif = (Notification) obj;

    if ( notif.getBroadcasted() ) {
      userDAO.select(new AbstractSink() {
        @Override
        public void put(Object o, Detachable d) {
          User user = (User) o;
          send(user, notif, x);
        }
      });
    } else if ( ! SafetyUtil.isEmpty(notif.getGroupId()) ) {
      userDAO.where(EQ(User.GROUP, notif.getGroupId())).select(new AbstractSink() {
        @Override
        public void put(Object o, Detachable d) {
          User user = (User) o;
          send(user, notif, x);
        }
      });
    }

    if ( SafetyUtil.isEmpty(notif.getGroupId()) && ! notif.getBroadcasted() ) {
      return super.put_(x, notif);
    }

    return obj;
  }

  public void send(User user, Notification notif, X x) {
    Notification notification = (Notification) notif.fclone();
    notification.setId(0L);
    notification.setUserId(user.getId());
    notification.setBroadcasted(false);
    notification.setGroupId(null);
    ((DAO) x.get("notificationDAO")).put_(x, notification);
  }
}

@@ -195,21 +195,84 @@
 oam.
-nanos.auth.Us
+mlang.sink.Count;%0Aimport foam.nanos.auth.User;%0Aimport foam.nanos.logger.Logg
 er;%0A
@@ -921,32 +921,48 @@
 pId()) ) %7B%0A     
+ DAO receivers =
  userDAO.where(E
@@ -995,16 +995,366 @@
 upId()))
+;%0A      Count count = (Count) receivers.select(new Count());%0A      Logger logger = (Logger) x.get(%22logger%22);%0A      if ( count.getValue() == 0 ) %7B%0A        logger.warning(%22Notification %22 + notif.getNotificationType() +%0A          %22 will not be saved to notificationDAO because no users exist in the group %22 + notif.getGroupId());%0A      %7D%0A      receivers
 .select(

add a warning message