package meerkat.crypto.dkg.comm;

import com.google.protobuf.InvalidProtocolBufferException;
import meerkat.comm.Channel;
import meerkat.protobuf.Comm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by Tzlil on 2/14/2016.
 *
 * an implementation of ReceiverCallback
 */
public abstract class MessageHandler implements Channel.ReceiverCallback {
    final Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * fixed value for broadcasting
     */
    public static final int BROADCAST = 0;

       /**
     * Handle a broadcast (or unicast) message.
     * If the message is invalid, the handler can throw an {@link InvalidProtocolBufferException}, in which
     * case the message will simply be ignored.
     * @param envelope
     */
    public abstract void handleMessage(Comm.BroadcastMessage envelope) throws InvalidProtocolBufferException;

    /**
     * Was this broadcastMessage was received by broadcast channel
     * @param broadcastMessage
     * @return broadcastMessage user destination == BROADCAST
     */
    public boolean isBroadcast(Comm.BroadcastMessage broadcastMessage){
        return broadcastMessage.getDestination() == BROADCAST;
    }

    @Override
    public void receiveMessage(Comm.BroadcastMessage envelope) {
        try {
            handleMessage(envelope);
        } catch (InvalidProtocolBufferException e) {
            logger.warn("Received invalid protocol buffer from channel", e);
        }
    }
}
