/*

Copyright (c) 2002-2005, Yauheni Akhotnikau
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

- Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.

- Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.

- The name of the author may not be used to endorse or promote products derived
from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
OF SUCH DAMAGE.

*/

/*
	ObjESSty-1
*/

/*!
	\file
	\brief Стандартная реализация интерфейса db_content_t.
*/

#include <iostream>

#include <oess_1/defs/h/ex.hpp>
#include <oess_1/defs/impl/h/catch_all.hpp>

#include <oess_1/defs/log/h/err.hpp>

#include <oess_1/db/impl/db_content/h/errno.hpp>
#include <oess_1/db/impl/db_content/h/std_db_content.hpp>

namespace oess_1 {

namespace db {

namespace impl {

namespace db_content {

//
// trans_owner_info_t
//

trans_owner_info_t::trans_owner_info_t()
{
}

trans_owner_info_t::~trans_owner_info_t()
{
}

void
trans_owner_info_t::begin(
	const std::string & client_id )
{
	m_owner = client_id;
}

void
trans_owner_info_t::commit()
{
	cleanup();
}

void
trans_owner_info_t::rollback()
{
	cleanup();
}

void
trans_owner_info_t::must_be_owner(
	const std::string & client_id ) const
{
	if( is_started() && client_id != m_owner )
		OESS_THROW_PHYSIC( err::c_transaction_in_progress,
			"transaction of another client in progress, owner: "
			<< m_owner )
}

bool
trans_owner_info_t::is_owner(
	const std::string & client_id ) const
{
	return ( is_started() && client_id == m_owner );
}

//
// create_std_db_content
//

std::auto_ptr< db_content_t >
create_std_db_content()
{
	return std::auto_ptr< db_content_t >( new std_db_content_t() );
}

//! \name Макросы для корректного начала и завершения системной транзакции.
//! \{

#define DB_CONTENT__SYS_TRANS_START \
	sys_trans_start(); \
	try \
		{

#define DB_CONTENT__SYS_TRANS_FINISH \
		} \
	catch( ... ) \
		{ \
			careful_sys_trans_rollback(); \
			throw; \
		} \
	sys_trans_finish();

//! \}

//
// std_db_content_t
//

std_db_content_t::std_db_content_t()
:	m_is_open( false )
,	m_trans_deep( 0 )
{
}

std_db_content_t::~std_db_content_t()
{
	cleanup();
}

void
std_db_content_t::open(
	const std::string & name,
	const oess_1::db::storage::config_t & config,
	bool is_read_only,
	bool is_auto_repair_enabled )
{
	if( m_is_open )
		OESS_THROW_LOGIC( err::c_db_open,
			"physic_name: " << name
			<< ", is_read_only: " << is_read_only
			<< ", is_auto_repair_enabled: "
			<< is_auto_repair_enabled )

	try
	{
		m_storage.reset( oess_1::db::storage::open_stream_storage(
				name, config, is_read_only, is_auto_repair_enabled ) );

		m_client_map_ptr = create_std_client_map();

		m_is_open = true;
	}
	catch( ... )
	{
		// Если что-то произошно, то возвращаемся в исходное состояние.
		cleanup();
		throw;
	}
}

void
std_db_content_t::client_attach(
	const std::string & client_id )
{
	must_be_open();

	m_client_map_ptr->attach( client_id );
}

void
std_db_content_t::client_detach(
	const std::string & client_id )
{
	must_be_open();

	if( m_transaction_owner.is_owner( client_id ) )
		transaction_rollback( client_id );

	m_client_map_ptr->detach( client_id );
}

oess_1::uint_t
std_db_content_t::client_count() const
{
	must_be_open();

	return m_client_map_ptr->count();
}

void
std_db_content_t::slice_create(
	const std::string & client_id,
	const std::string & name )
{
	check_for_client( client_id, must_be_transaction_owner );

	// Ошибка об не уникальном имени раздела не
	// считается ошибкой. Т.е. пользователь пытается
	// создать уже существующий раздел и это ему удается --
	// после его запроса раздел в БД есть.
	if( !m_storage->stream_is_exists( name ) )
	{
		// Создаем поток и обновляем карту разделов
		// внутри транзакции.
		DB_CONTENT__SYS_TRANS_START

		m_storage->stream_create( name );

		DB_CONTENT__SYS_TRANS_FINISH
	}
}

void
std_db_content_t::slice_destroy(
	const std::string & client_id,
	const std::string & name )
{
	check_for_client( client_id, must_be_transaction_owner );

	{
		// Обновляем карту разделов внутри транзакции.
		DB_CONTENT__SYS_TRANS_START

		m_storage->stream_destroy( name );

		DB_CONTENT__SYS_TRANS_FINISH
	}
}

bool
std_db_content_t::slice_is_exists(
	const std::string & client_id,
	const std::string & name )
{
	check_for_client( client_id, must_be_transaction_owner );

	return m_storage->stream_is_exists( name );
}

std::set< std::string >
std_db_content_t::slice_names(
	const std::string & client_id )
{
	check_for_client( client_id, must_be_transaction_owner );

	return m_storage->stream_names();
}

oess_1::ent_id_t
std_db_content_t::ent_create(
	const std::string & client_id,
	const std::string & slice_name,
	oess_1::io::istream_t & ent_value,
	oess_1::uint_t ent_size )
{
	check_for_client( client_id, must_be_transaction_owner );

	// Раздел должен существовать.
	oess_1::db::storage::entity_stream_t & db_slice =
			m_storage->stream_get( slice_name );

	oess_1::db::storage::chain_id_t ent_chain =
			oess_1::db::storage::invalid_chain_id;

	// Осталось только в системной транзакции поместить
	// сущность в хранилище.
	DB_CONTENT__SYS_TRANS_START

	ent_chain = db_slice.entity_create( ent_value, ent_size );

	DB_CONTENT__SYS_TRANS_FINISH

	return oess_1::ent_id_t( db_slice.id(), ent_chain );
}

void
std_db_content_t::ent_destroy(
	const std::string & client_id,
	const oess_1::ent_id_t & ent_id )
{
	check_for_client( client_id, must_be_transaction_owner );

	// Раздел должен существовать.
	oess_1::db::storage::entity_stream_t & db_slice =
			m_storage->stream_get( ent_id.m_slice_id );

	DB_CONTENT__SYS_TRANS_START

	db_slice.entity_destroy( ent_id.m_ent_id );

	DB_CONTENT__SYS_TRANS_FINISH
}

void
std_db_content_t::ent_destroy_all(
	const std::string & client_id,
	const std::string & slice_name )
{
	check_for_client( client_id, must_be_transaction_owner );

	// Раздел должен существовать.
	oess_1::db::storage::entity_stream_t & db_slice =
			m_storage->stream_get( slice_name );

	// Осталось только в системной транзакции удалить все
	// сущности из раздела.
	DB_CONTENT__SYS_TRANS_START

	db_slice.entity_destroy_all();

	DB_CONTENT__SYS_TRANS_FINISH
}

void
std_db_content_t::ent_load(
	const std::string & client_id,
	const oess_1::ent_id_t & ent_id,
	oess_1::io::ostream_t & ent_value )
{
	check_for_client( client_id, must_be_transaction_owner );

	// Раздел должен существовать.
	oess_1::db::storage::entity_stream_t & db_slice =
			m_storage->stream_get( ent_id.m_slice_id );

	// Загружаем значение сущности.
	db_slice.entity_load( ent_id.m_ent_id, ent_value );
}

void
std_db_content_t::ent_update(
	const std::string & client_id,
	const oess_1::ent_id_t & ent_id,
	oess_1::io::istream_t & ent_value,
	oess_1::uint_t ent_size )
{
	check_for_client( client_id, must_be_transaction_owner );

	// Раздел должен существовать.
	oess_1::db::storage::entity_stream_t & db_slice =
			m_storage->stream_get( ent_id.m_slice_id );

	// Осталось только в системной транзакции поместить
	// сущность в хранилище.
	DB_CONTENT__SYS_TRANS_START

	db_slice.entity_update( ent_id.m_ent_id, ent_value, ent_size );

	DB_CONTENT__SYS_TRANS_FINISH
}

oess_1::ent_id_t
std_db_content_t::ent_find_next(
	const std::string & client_id,
	const std::string & slice_name,
	const oess_1::ent_id_t & ent_id )
{
	check_for_client( client_id, must_be_transaction_owner );

	// Раздел должен существовать.
	oess_1::db::storage::entity_stream_t & db_slice =
			slice_for_entity_search( slice_name, ent_id );

	oess_1::ent_id_t next_ent_id( db_slice.id(),
			oess_1::db::storage::invalid_chain_id );

	// Значение NULL для oess_1::ent_id_t и для
	// идентификатора сущности в потоке хранилища
	// кодируются по разному.
	oess_1::db::storage::chain_id_t start_from = ( ent_id ?
		ent_id.m_ent_id :
		oess_1::db::storage::invalid_chain_id );

	next_ent_id.m_ent_id = db_slice.entity_find_next( start_from );
	// Если ничего не нашли, то нужно возвращать эквивалент NULL.
	if( oess_1::db::storage::invalid_chain_id == next_ent_id.m_ent_id )
		next_ent_id.make_null();

	return next_ent_id;
}

void
std_db_content_t::transaction_begin(
	const std::string & client_id )
{
	check_for_client( client_id, connection_only );

	// Вложенные транзакции не допускаются.
	if( m_transaction_owner.is_started() )
		OESS_THROW_LOGIC( err::c_transaction_in_progress,
			"transaction already started" )

	// Начинаем системную транзакцию. А этот клиент становится
	// владельцем транзакции.
	m_transaction_owner.begin( client_id );
	sys_trans_start();
}

void
std_db_content_t::transaction_commit(
	const std::string & client_id )
{
	check_for_client( client_id, must_be_transaction_owner );

	m_transaction_owner.commit();
	sys_trans_finish();
}

void
std_db_content_t::transaction_rollback(
	const std::string & client_id )
{
	check_for_client( client_id, must_be_transaction_owner );

	m_transaction_owner.rollback();
	m_trans_deep = 0;
	m_storage->trans_rollback();
}

void
std_db_content_t::sys_trans_start()
{
	if( !m_trans_deep++ )
		m_storage->trans_start();
}

void
std_db_content_t::sys_trans_finish()
{
	if( !( --m_trans_deep ) )
	{
		m_storage->trans_commit();
	}
}

void
std_db_content_t::careful_sys_trans_rollback()
{
	if( m_trans_deep )
	{
		if( !( --m_trans_deep ) )
			__OESS_CATCH_ALL( m_storage->trans_rollback(); )
	}
}

void
std_db_content_t::cleanup()
{
	__OESS_CATCH_ALL( m_client_map_ptr.reset(); )

	__OESS_CATCH_ALL( m_storage.destroy(); )

	m_is_open = false;
	m_trans_deep = 0;
	m_transaction_owner.cleanup();
}

void
std_db_content_t::must_be_open() const
{
	if( !m_is_open )
		OESS_THROW_LOGIC( err::c_db_not_open,
			"DB not open" )
}

void
std_db_content_t::check_for_client(
	const std::string & client_id,
	unsigned int actions ) const
{
	must_be_open();
	// Клиент должен быть подключен.
	m_client_map_ptr->find( client_id );

	if( must_be_transaction_owner & actions )
		m_transaction_owner.must_be_owner( client_id );
}

oess_1::db::storage::entity_stream_t &
std_db_content_t::slice_for_entity_search(
	const std::string & slice_name,
	const oess_1::ent_id_t & ent_id )
{
	if( ent_id )
		// Это продолжение поиска.
		return m_storage->stream_get( ent_id.m_slice_id );
	else if( !slice_name.length() )
		OESS_THROW_LOGIC( err::c_invalid_search_param,
			"ent_find_next: slice_name == NULL && ent_id == NULL" )

	return m_storage->stream_get( slice_name );
}

} /* namespace db_content */

} /* namespace impl */

} /* namespace db */

} /* namespace oess_1 */
