package id.iptek.utms.agent.worker;

import com.google.gson.Gson;
import id.iptek.utms.agent.AppConfig;
import id.iptek.utms.agent.model.HeartBeat;
import id.iptek.utms.agent.queue.ConsumerMode;
import id.iptek.utms.agent.queue.DelayMessageQueue;
import id.iptek.utms.agent.queue.HeartBeatQueueMessageHandler;
import id.iptek.utms.agent.util.Singleton;
import java.util.Date;
import java.util.UUID;
import org.eclipse.paho.client.mqttv3.MqttMessage;

/**
 *
 * @author Jaka
 */
public class HeartbeatWorker extends Worker {

    public HeartbeatWorker() {
    }

    @Override
    void init(String consumerName, AppConfig appConfig) throws Exception {
        super.init(consumerName, appConfig);
        
        DelayMessageQueue<HeartBeat> queue = (DelayMessageQueue<HeartBeat>) Singleton.getInstance(HeartBeatQueueMessageHandler.NAME).getObject();
        ConsumerMode mode = ConsumerMode.valueOf(appConfig.get("mqtt.consumer."+consumerName+".consumermode", "SINGLE"));
        int batchCapacity = appConfig.getAsInt("mqtt.consumer."+consumerName+".batch.capacity", 10);
        queue.setCapacity(batchCapacity);
        queue.setMode(mode);
    }

    @Override
    protected void doSomething() throws Exception {
        // do something
    }

    @Override
    public void messageArrived(String string, MqttMessage mm) throws Exception {
        try {
            String json = new String(mm.getPayload());
            logger.debug("<< " + json + " (" + mm.getId() + " - " + mm.getQos() + ")");
            Gson gson = new Gson();
            HeartBeat heartbeatReq = gson.fromJson(json, HeartBeat.class);
            if(!"HEARTBEAT".equals(heartbeatReq.getReqType())) {
                // skip message
                return;
            }
            
            // set id
            heartbeatReq.setId(UUID.randomUUID().toString());
            heartbeatReq.setCreateTime(new Date());
            
            DelayMessageQueue<HeartBeat> queue = (DelayMessageQueue<HeartBeat>) Singleton.getInstance(HeartBeatQueueMessageHandler.NAME).getObject();
            boolean queued = queue.add(heartbeatReq);
            if(!queued) {
                logger.error("Heartbeat NOT queued: {}", queued);
            }
        } catch (Exception ex) {
            logger.error("Error processing heartbeat: {}", ex.getMessage(), ex);
        }
    }
}
