//------------------------------------------------------------------------------
//	Copyright (C) 2009, 2010 Humboldt-Universitaet zu Berlin
//
//	This library is free software; you can redistribute it and/or
//	modify it under the terms of the GNU Lesser General Public
//	License as published by the Free Software Foundation; either
//	version 2.1 of the License, or (at your option) any later version.
//
//	This library is distributed in the hope that it will be useful,
//	but WITHOUT ANY WARRANTY; without even the implied warranty of
//	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//	Lesser General Public License for more details.
//
//	You should have received a copy of the GNU Lesser General Public
//	License along with this library; if not, write to the Free Software
//	Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//------------------------------------------------------------------------------

/**
 * @file DatabaseWriter.h
 * @author Ronald Kluth
 * @date created at 2009/02/18
 * @brief Declaration of class odemx::data::output::DatabaseWriter
 * @sa DatabaseWriter.cpp
 * @since 3.0
 */

#ifndef ODEMX_DATA_OUTPUT_DATABASEWRITER_INCLUDED
#define ODEMX_DATA_OUTPUT_DATABASEWRITER_INCLUDED

#include <odemx/setup.h>
#include <odemx/data/buffer/SimRecordBuffer.h>
#include <CppLog/output/DatabaseAccessor.h>
#include <CppLog/Consumer.h>

#include <string>
#ifdef _MSC_VER
#include <memory>
#else
#include <tr1/memory>
#endif

//----------------------------------------------------------forward declarations

namespace odemx {

namespace base { class Simulation; }

namespace data {
namespace output {

class TimeFormat;

//-----------------------------------------------------------header declarations

/**
 * @brief Log consumer type that writes simulation records to a database
 * @ingroup data
 * @author Ronald Kluth
 * @since 3.0
 * @see odemx::data::Producer
 *
 * This class enables ODEMx to write log records to a relational database.
 * The default database management system use by ODEMx is SQLite, which is
 * usable out of the box. In order to use an external DBMS via ODBC, the macro
 * ODEMX_USE_ODBC must be defined in file odemx/setup.h.
 *
 * The data is spread over three different tables:
 * @li odemx_simulation_run
 * @li odemx_sim_record
 * @li odemx_sim_record_detail
 *
 * For performance reasons, all data is buffered up to a given limit. When that
 * limit is reached, or the method flush is called, the stored data is written
 * to the database in a single transaction. This speeds it up dramatically.
 */
class DatabaseWriter
:	public Log::Consumer< SimRecord >
{
public:
	/// Map type to associate simulation pointers with their table key
	typedef std::map< const base::Simulation*, TableKey > SimIdMap;

	/**
	 * @brief Creation via static method to enforce shared_ptr usage
	 * @param connectionString The connection string for the database
	 * @param bufferLimit The amount of records to buffer before writing to the database
	 * @return A shared_ptr to the database writer
	 *
	 * Upon creation, the DatabaseWriter object will automatically connect to
	 * the database described by the connection string. In the case of SQLite
	 * this is a simple file name. When using ODBC, however, it must provide
	 * the driver, user ID, password, database name, server address and port.
	 */
	static std::tr1::shared_ptr< DatabaseWriter > create(
			const std::string& connectionString,
			buffer::SimRecordBuffer::SizeType bufferLimit = 100000 );

	/**
	 * @brief  Destruction
	 *
	 * If the record buffer is not empty, a call to flush will be made in
	 * order to write all remaining records to the database.
	 *
	 * @note This constructor does not throw. Therefore, any exceptions
	 * thrown by the call to flush will not be propagated. Call flush before
	 * destruction in order to examine such exceptions.
	 */
	virtual ~DatabaseWriter();

	/**
	 * @brief Write buffered data to the connected database
	 *
	 * This method uses the DatabaseAccessor's method @c storeData to write
	 * the buffer contents to the database within one transaction, and finally
	 * clears the buffer.
	 */
	void flush();

	/**
	 * @brief Set a new time formatter
	 * @see odemx::data::output::GermanTime, odemx::data::output::Iso8601Time
	 *
	 * The default formatter simply outputs SimTime values, i.e. numbers
	 * as strings. ODEMx also supports the formatting of the simulation time
	 * in the official German and a simplified ISO 8601 format.
	 *
	 * @note The function takes ownership of the pointer and deletes it
	 * automatically when the writer is destroyed or the format is changed.
	 * Therefore, you must use dynamically allocated objects.
	 */
	void setTimeFormat( TimeFormat* timeFormat );

	/// Get read access to the internal buffer, provided for testing purposes
	const buffer::SimRecordBuffer& getBuffer() const;

private:
	/**
	 * @brief Implementation of the consumer interface function
	 * @param channelId The ID of the forwarding log channel
	 * @param record A record describing a current simulation event
	 *
	 * This consumer interface definition first checks the current simulation
	 * context to account for multiple simulations (in the same program).
	 * It then stores the record in the buffer by copying the necessary data.
	 * Finally, if the buffer is full, data gets automatically written to
	 * the database by calling @c flush.
	 */
	virtual void consume( const Log::ChannelId channelId, const SimRecord& record );

private:
	/// Database access layer provided by the logging library
	Log::DatabaseAccessor db_;
	/// Buffer for stored sim record data
	buffer::SimRecordBuffer recordBuffer_;
	/// Pointer to simulations context the last record belonged to
	const base::Simulation* lastRecordSim_;
	/// Map containing the table keys of different simulation objects (in the same program)
	SimIdMap simIds_;
	/// Key of the simulation context the current record belongs to (is buffered too)
	TableKey currentSimKey_;
	/// Key of the last successfully inserted record, needed as foreign key for detail table
	TableKey currentRecordKey_;
	/// SQL inserter object to put data into table odemx_simulation_run
	std::auto_ptr< Log::DatabaseAccessor::SqlInserter > simInserter_;
	/// SQL inserter object to put data into table odemx_sim_record
	std::auto_ptr< Log::DatabaseAccessor::SqlInserter > recordInserter_;
	/// SQL inserter object to put data into table odemx_sim_record_detail
	std::auto_ptr< Log::DatabaseAccessor::SqlInserter > detailInserter_;
	/// Pointer to the time formatter
	std::auto_ptr< TimeFormat > timeFormat_;

private:
	/// Creates tables if necessary, initializes the SQL inserters with prepared statements
	void initialize();
	/// Checks if the tables exist, and creates them if needed
	void checkTables();
	/// Checks if the simulation context has changed and adjusts @c currentSimKey_ accordingly
	void checkRecordSim( const base::Simulation* currentSim );
	/// Inserts simulation entries for every new simulation context encountered
	void insertSimIntoTable( const base::Simulation* sim );
	/// Inserts a stored record and its details into the respective tables
	void insertRecord( const buffer::SimRecordBuffer::StoredRecord& record );

private:
	/// Construction private, use @c create instead
	DatabaseWriter( const std::string& connectionString,
			buffer::SimRecordBuffer::SizeType bufferLimit );
	/// Non-copyable
	DatabaseWriter( const DatabaseWriter& );
	/// Non-assignable
	DatabaseWriter& operator=( const DatabaseWriter& );
};

/// Smart pointer type to manage DatabaseWriter objects
typedef std::tr1::shared_ptr< DatabaseWriter > DatabaseWriterPtr;

} } } // namespace odemx::data::output

#endif /* ODEMX_DATA_OUTPUT_DATABASEWRITER_INCLUDED */
