package org.josast.CubesatSim.influxDB;

import java.util.logging.Logger;

import org.influxdb.InfluxDB;
import org.influxdb.InfluxDBFactory;
import org.influxdb.InfluxDBIOException;
import org.influxdb.dto.BatchPoints;
import org.influxdb.dto.Pong;

/**
 * Manage InflusDB Instance
 * 
 * @author christophe
 *
 */
public class InfluxDBInstance {

	private Logger log = Logger.getLogger(getClass().getName());

	static InfluxDBInstance influxDB = null;
	private InfluxDB influxdatabase = null;
	private String databasename;

	/**
	 * @return the databasename
	 */
	public String getDatabasename() {
		return databasename;
	}

	/**
	 * @param databasename the databasename to set
	 */
	public void setDatabasename(String databasename) {
		this.databasename = databasename;
	}

	private InfluxDBInstance() {

	}

	/** Holder */
	private static class SingletonHolder {
		/** Instance unique non pr�initialis�e */
		private final static InfluxDBInstance instance = new InfluxDBInstance();
	}

	@SuppressWarnings("deprecation")
	public void createDataBase(String database) {

		if (influxdatabase.databaseExists(database) == false) {
			log.info("new database created");
			influxdatabase.createDatabase(database);
		}
		log.info("database already exist");
		databasename = database;
	}

	public void conect(String databaseURL, String userName, String password) {
		
		try 
		{

		influxdatabase = InfluxDBFactory.connect(databaseURL, userName, password);
		Pong response = influxdatabase.ping();
		if (response.getVersion().equalsIgnoreCase("unknown")) {
			log.severe("Error pinging server database  : " + databaseURL);

		} else {
			log.info(response.getVersion());
		}
		}
		catch (InfluxDBIOException e)
		{
			log.severe("InfluxDB database not reach");
		
		}


	}

	/** Point d'acc�s pour l'instance unique du singleton */
	public static InfluxDBInstance getInstance() {
		return SingletonHolder.instance;
	}

	public void write(BatchPoints batchPoints) {
		if (influxdatabase != null) {
			influxdatabase.write(batchPoints);
		} else {
			log.severe("Database connection not initialised");
		}
	}

}
