package cs451.net.handler;

import cs451.net.event.NetEvent;
import cs451.parser.Host;
import cs451.parser.Parser;

import java.util.List;
import java.util.stream.Collectors;

/**
 * NetEventHandler for Best Effort Broadcast
 *
 * Send: Send to all hosts (deliver to self)
 *
 * @author C. Hölzl
 */
public class NetHandlerBEB extends NetEventHandlerAbstract {

    private List<Host> hosts;
    private Host h;

    public NetHandlerBEB(Class<? extends NetEventHandlerAbstract> deliverLayer, Class<? extends NetEventHandlerAbstract> broadcastLayer) {
        super(deliverLayer,broadcastLayer);
    }

    @Override
    public void broadcast(NetEvent ne) {
        deliverNextAsync(NetEvent.Message(h,ne.message));
        hosts.parallelStream().forEach(h -> broadcastNextSync(NetEvent.Message(h, ne.message)));
    }

    @Override
    public void start(Host h, Parser p) {
        super.start(h,p);
        this.h = h;
        hosts = p.hosts().stream().filter(ch -> ch.getId()!=h.getId()).collect(Collectors.toList());
    }

}
