package id.iptek.utms.agent.worker;

import id.iptek.utms.agent.AppConfig;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author Jaka
 */
public final class WorkerFactory {
    
    private static WorkerFactory self;
    private static final Logger logger = LoggerFactory.getLogger(WorkerFactory.class);

    private WorkerFactory() {
    }
    
    public List<Worker> buildWorkers(AppConfig config) throws Exception {
        List<Worker> workers = new ArrayList<>();
        try {
            String[] consumerNames = config.getAll("mqtt.consumers");
            
            logger.info("Build workers ...");
            for(String consumerName : consumerNames) {
                logger.debug("Build worker: '{}'", consumerName);
                String workerClass = config.get("mqtt.consumer." + consumerName + ".workerclass");
                Class clazz = Class.forName(workerClass);
                int _threads = config.getAsInt("mqtt.consumer." + consumerName + ".threads", 1);
                
                for(int a = 0; a < _threads; a++) {
                    Worker worker = (Worker) clazz.newInstance();
                    worker.init(consumerName, config);
                    workers.add(worker);
                }
            }
            logger.info("... done build workers.");
        } finally {
        }
        return workers;
    }
    
    public static WorkerFactory getInstance() {
        if(self == null) {
            self = new WorkerFactory();
        }
        return self;
    }
}
