package id.iptek.utms.agent.worker;

import com.google.gson.Gson;
import id.iptek.utms.agent.AppConfig;
import id.iptek.utms.agent.queue.ConsumerMode;
import id.iptek.utms.agent.queue.DelayMessageQueue;
import id.iptek.utms.agent.queue.DeviceInitQueueMessageHandler;
import id.iptek.utms.agent.util.Singleton;
import java.util.Map;
import org.eclipse.paho.client.mqttv3.MqttMessage;

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

    public DeviceInitWorker() {
    }

    @Override
    void init(String consumerName, AppConfig appConfig) throws Exception {
        super.init(consumerName, appConfig);
        
        DelayMessageQueue<Map> queue = (DelayMessageQueue<Map>) Singleton.getInstance(DeviceInitQueueMessageHandler.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
    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();
            Map map = gson.fromJson(json, Map.class);

            String terminalSN = (String) map.get("device_sn");
            if(terminalSN == null) {
                logger.debug("SN Information null!");
                return;
            }
            
            // put mqttclient to the map
            map.put("MQTT", mqttClient);
            
            DelayMessageQueue<Map> queue = (DelayMessageQueue<Map>) Singleton.getInstance(DeviceInitQueueMessageHandler.NAME).getObject();
            boolean queued = queue.add(map);
            if(!queued) {
                logger.error("Init request NOT queued: {}", queued);
            }
        } catch (Exception ex) {
            logger.error("Init: {}", ex.getMessage(), ex);
        }
    }
}
