package org.eclipse.kura.example.ble.tisensortag;

import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.eclipse.kura.message.KuraPayload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mongodb.BasicDBObject;
import com.mongodb.BasicDBObjectBuilder;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.WriteConcern;

public class MongoSensorDocWrapper {
	
	private static final Logger s_logger = LoggerFactory.getLogger(BluetoothLe.class);
	
	int idCode;
	MongoClient mongo = null;
	DB db = null;
	
	public MongoSensorDocWrapper() {
		if(null == mongo) {
			connectMongo();
		}
		if(null == db) {
			db = getDBFromMongo(mongo);
		}
	}

	private void connectMongo() {
		mongo = getMongoClient();
		s_logger.info("Made it past connect => ");
		db = getDBFromMongo(mongo);
	}
	
	//For testing, build a sample KuraPayload and publish it to the MongoDB specified in ConnectionInfo
	public void publish() {
		connectMongo(); <=== This never completes, see below
	
		try {
			publishMongo(mongo, db, buildSensorKuraPayload());
		}
		catch(UnknownHostException uhe) {
			System.out.println("Unknown Host");
		}
		destroyMongoInstance();
	}

	public void publish(KuraPayload payload) {
		connectMongo();
		try {
			publishMongo(mongo, db, payload);
		}
		catch(UnknownHostException uhe) {
			System.out.println("Unknown Host");
		}
		destroyMongoInstance();
	}
	private void destroyMongoInstance() {
		if(null != mongo) {
			mongo.close();
		}
		mongo=null;
	}	

	private MongoClient getMongoClient() {
				
		return new MongoClient("localhost", 27017)  <=== This never completes
	}