package id.iptek.utms.agent.queue;

import id.iptek.utms.agent.dao.HeartbeatDao;
import id.iptek.utms.agent.model.HeartBeat;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author jakar
 */
public class HeartBeatQueueMessageHandler implements QueueMessageHandler<HeartBeat> {

    public final static String NAME = "HEARTBEAT_QUEUE_HANDLER";
    private Logger logger = LoggerFactory.getLogger(getClass());
    private HeartbeatDao dao = new HeartbeatDao();
    
    public HeartBeatQueueMessageHandler() {
    }

    @Override
    public boolean handleMessage(HeartBeat message) {
        try {
            logger.debug("Saving heartbeat: {}", message);
            long start = System.currentTimeMillis();
            boolean saved = dao.save(message);
            long end = System.currentTimeMillis();
            logger.debug("Saved in {}ms", (end-start));
            return saved;
        } catch(Exception ex) {
            logger.error("Error handling heartbeat: {}", ex.getMessage(), ex);
            return false;
        }
    }

    @Override
    public boolean handleMessages(List<HeartBeat> messages) {
        try {
            logger.debug("Saving list of heartbeats: {}", messages.size());
            long start = System.currentTimeMillis();
            boolean saved = dao.saveAll(messages);
            long end = System.currentTimeMillis();
            logger.debug("Saved in {}ms", (end-start));
            return saved;
        } catch(Exception ex) {
            logger.error("Error handling list of heartbeats: {}", ex.getMessage(), ex);
            return false;
        }
    }
    
}
