/*

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.

*/

#include <map>

#include <ace/Thread_Mutex.h>
#include <ace/Guard_T.h>

#include <auto_ptr_3/h/obj_ptr.hpp>

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

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

#include <oess_1/stdsn/h/errno.hpp>
#include <oess_1/stdsn/h/serializable.hpp>
#include <oess_1/stdsn/h/shptr.hpp>

namespace oess_1 {

namespace stdsn {

//
// unknown_extension_t
//

unknown_extension_t::unknown_extension_t()
	{}
unknown_extension_t::unknown_extension_t(
	const std::string & data )
	:	m_data( data )
	{}

const std::string &
unknown_extension_t::get() const
	{
		return m_data;
	}

void
unknown_extension_t::clear()
	{
		m_data.erase( m_data.begin(), m_data.end() );
	}

//
// all_unknown_extensions_data_t
//

/*!
	\since v.1.2.0
	\brief Структура реального содержимого объекта
		%all_unknown_extensions_t.
*/
struct	all_unknown_extensions_data_t
	{
		//! Тип ассоциативной карты расширений типов.
		typedef std::map< std::string, unknown_extension_t > map_t;

		//! Карта расширений типов.
		map_t	m_map;

		/*!
			Ссылка на этот объект будет возвращаться в случае
			отсутствия расширения для типа.
		*/
		unknown_extension_t	m_empty;

		all_unknown_extensions_data_t()
			{}
		all_unknown_extensions_data_t(
			const all_unknown_extensions_data_t & o )
			{
				(*this) = o;
			}

		all_unknown_extensions_data_t &
		operator=(
			const all_unknown_extensions_data_t & o )
			{
				m_map = o.m_map;
				m_empty = o.m_empty;
				return *this;
			}
	};

//
// all_unknown_extension_t
//

all_unknown_extensions_t::all_unknown_extensions_t()
	:	m_data( new all_unknown_extensions_data_t() )
	{}

all_unknown_extensions_t::all_unknown_extensions_t(
	const all_unknown_extensions_t & o )
	{
		(*this) = o;
	}

all_unknown_extensions_t::~all_unknown_extensions_t()
	{}

all_unknown_extensions_t &
all_unknown_extensions_t::operator=(
	const all_unknown_extensions_t & o )
	{
		if( &o != this )
			m_data.reset( new all_unknown_extensions_data_t(
				*( o.m_data ) ) );

		return *this;
	}

const unknown_extension_t &
all_unknown_extensions_t::get( const std::string & type_name ) const
	{
		all_unknown_extensions_data_t::map_t::const_iterator it =
			m_data->m_map.find( type_name );
		if( it != m_data->m_map.end() )
			{
				return it->second;
			}

		return m_data->m_empty;
	}

unknown_extension_t &
all_unknown_extensions_t::get( const std::string & type_name )
	{
		return m_data->m_map[ type_name ];
	}

void
all_unknown_extensions_t::drop()
	{
		m_data->m_map.clear();
	}

//
// subclass_extension_path_t::item_t
//

subclass_extension_path_t::item_t::item_t()
	{}
subclass_extension_path_t::item_t::item_t(
	const std::string & type_name,
	const std::string & scheme )
	:	m_type_name( type_name )
	,	m_scheme( scheme )
	{}

subclass_extension_path_t::item_t::item_t(
	const item_t & o )
	:	m_type_name( o.m_type_name )
	,	m_scheme( o.m_scheme )
	{}

subclass_extension_path_t::item_t &
subclass_extension_path_t::item_t::operator=(
	const item_t & o )
	{
		if( &o != this )
			{
				m_type_name = o.m_type_name;
				m_scheme = o.m_scheme;
			}

		return *this;
	}

//
// subclass_extension_path_t
//

subclass_extension_path_t::subclass_extension_path_t()
	{}
subclass_extension_path_t::subclass_extension_path_t(
	const subclass_extension_path_t & o )
	{
		(*this) = o;
	}
subclass_extension_path_t::~subclass_extension_path_t()
	{}

subclass_extension_path_t &
subclass_extension_path_t::operator=(
	const subclass_extension_path_t & o )
	{
		if( &o != this )
			{
				m_list = o.m_list;
			}

		return *this;
	}

void
subclass_extension_path_t::push_back(
	const std::string & type_name,
	const std::string & type_scheme )
	{
		m_list.push_back( item_t( type_name, type_scheme ) );
	}

oess_1::uint_t
subclass_extension_path_t::size() const
	{
		return m_list.size();
	}

subclass_extension_path_t::const_iterator
subclass_extension_path_t::begin() const
	{
		return m_list.begin();
	}

subclass_extension_path_t::const_iterator
subclass_extension_path_t::end() const
	{
		return m_list.end();
	}

bool
subclass_extension_path_t::operator==(
	const subclass_extension_path_t & o ) const
	{
		const_iterator
			i1 = begin(), i1_end = end(),
			i2 = o.begin(), i2_end = o.end();
		for( ;
			i1 != i1_end && i2 != i2_end;
			++i1, ++i2 )
			{
				if( i1->m_type_name != i2->m_type_name )
					return false;
			}

		return ( i1 == i1_end && i2 == i2_end );
	}

//
// serializable_t::oess_serializer_t
//

const std::string &
oess_1::stdsn::serializable_t::oess_serializer_t::type_name()
	{
		return serializable_t::oess_serializable_t_name();
	}

oess_1::stdsn::serializable_t *
oess_1::stdsn::serializable_t::oess_serializer_t::factory()
	{
		return 0;
	}

const std::string &
oess_1::stdsn::serializable_t::oess_serializer_t::scheme()
	{
		static std::string s(
				"{type {abstract } oess_1::stdsn::serializable_t }"
			);
		return s;
	}

//
// serializable_t
//

serializable_t::serializable_t()
	{}

serializable_t::serializable_t(
	const serializable_t & o )
	{
		(*this) = o;
	}

serializable_t::~serializable_t()
	{}

serializable_t &
serializable_t::operator=(
	const serializable_t & o )
	{
		if( &o != this )
			{
				m_oess_unknown_subclass_extension_path.reset();
				if( o.m_oess_unknown_subclass_extension_path.get() )
					m_oess_unknown_subclass_extension_path.reset(
						new subclass_extension_path_t(
							*(o.m_oess_unknown_subclass_extension_path) ) );
   
				m_oess_unknown_subclass_extension =
					o.m_oess_unknown_subclass_extension;
				m_oess_unknown_extensions =
					o.m_oess_unknown_extensions;
			}

		return *this;
	}

std::string &
serializable_t::oess_serializable_t_name()
	{
		static std::string name( "oess_1::stdsn::serializable_t" );
		return name;
	}

void
serializable_t::oess_pre_pack() const
	{}

void
serializable_t::oess_post_pack() const
	{}

void
serializable_t::oess_pre_unpack()
	{}

void
serializable_t::oess_post_unpack()
	{}

void
serializable_t::oess_store_unknown_subclass_extension_path(
	const subclass_extension_path_t & path )
	{
		m_oess_unknown_subclass_extension_path.reset(
			new subclass_extension_path_t( path ) );
	}

const subclass_extension_path_t *
serializable_t::oess_unknown_subclass_extension_path() const
	{
		return m_oess_unknown_subclass_extension_path.get();
	}

void
serializable_t::oess_drop_unknown_extensions()
	{
		m_oess_unknown_subclass_extension_path.reset();
		m_oess_unknown_subclass_extension.clear();
		m_oess_unknown_extensions.drop();
	}

const unknown_extension_t &
serializable_t::oess_unknown_subclass_extension() const
	{
		return m_oess_unknown_subclass_extension;
	}

unknown_extension_t &
serializable_t::oess_writeable_unknown_subclass_extension()
	{
		return m_oess_unknown_subclass_extension;
	}

const unknown_extension_t &
serializable_t::oess_lo_unknown_extension(
	const std::string & type_name ) const
	{
		return m_oess_unknown_extensions.get( type_name );
	}

unknown_extension_t &
serializable_t::oess_lo_writeable_unknown_extension(
	const std::string & type_name )
	{
		return m_oess_unknown_extensions.get( type_name );
	}

OESS_1__STDSN__FUNC( oent_t & )
operator<<( oent_t & writter, const serializable_t & o )
{
	o.oess_pack( writter );
	return writter;
}

OESS_1__STDSN__FUNC( ient_t & )
operator>>( ient_t & reader, serializable_t & o )
{
	o.oess_unpack( reader );
	return reader;
}

//
// factory_registrator_t
//

factory_registrator_t::factory_registrator_t(
	const char * type_name,
	pfn_factory_t factory ) :
	m_type_name( type_name ),
	m_factory( factory )
{
	obj_factory_t::reg( m_type_name, m_factory );
}

factory_registrator_t::~factory_registrator_t()
{
	obj_factory_t::dereg( m_type_name, m_factory );
}

//
// obj_factory_t
//

static ACE_Thread_Mutex &
obj_factory_lock()
	{
		static auto_ptr_3::obj_ptr_t< ACE_Thread_Mutex > lock;
		if( !lock.get() )
			lock.reset( new ACE_Thread_Mutex() );

		return *lock;
	}

typedef std::map< std::string, pfn_factory_t,
	std::less< std::string > >
	factory_map_t;

static factory_map_t &
factories()
	{
		static auto_ptr_3::obj_ptr_t< factory_map_t > map;
		if( !map.get() )
			map.reset( new factory_map_t() );

		return *map;
	}

void
obj_factory_t::reg(
	const std::string & type_name,
	pfn_factory_t factory )
{
	ACE_Guard< ACE_Thread_Mutex > lock( obj_factory_lock() );

	factory_map_t & f = factories();
	if( f.find( type_name ) == f.end() ) {
		f.insert( factory_map_t::value_type(
			type_name, factory ) );
	}
	else {
		OESS_1_LOG_ERR( "factory already registered. type_name: "
			<< type_name << ", factory "
			<< (void *)factory << "\n" )
	}
}

void
obj_factory_t::dereg(
	const std::string & type_name,
	pfn_factory_t factory )
{
	ACE_Guard< ACE_Thread_Mutex > lock( obj_factory_lock() );

	factory_map_t & f = factories();
	factory_map_t::iterator it = f.find( type_name );
	if( it != f.end() ) {
		if( factory == (*it).second )
			f.erase( it );
	}
}

serializable_t *
obj_factory_t::create(
	const std::string & type_to_create,
	const std::string & type_to_cast,
	const no_factory_action_t & no_factory_action )
{
	serializable_t * obj = 0;
	{
		ACE_Guard< ACE_Thread_Mutex > lock( obj_factory_lock() );
		factory_map_t & f = factories();
		factory_map_t::iterator it = f.find( type_to_create );
		if( it != f.end() )
		{
			pfn_factory_t pfn = (*it).second;
			obj = (*pfn)();
		}
	}

	if( obj )
	{
		auto_ptr_3::obj_ptr_t< serializable_t > safe_ptr( obj );
		if( !obj->oess_cast( type_to_cast ) )
			OESS_THROW_LOGIC(
				oess_1::stdsn::err::c_cast_fail,
				"type of object: " << obj->oess_type_name()
				<< ", cast to: " << type_to_cast )

		safe_ptr.clear();
	}
	else if( throw_exception == no_factory_action )
		OESS_THROW_LOGIC(
			oess_1::stdsn::err::c_factory_not_found,
			"type_to_create: " << type_to_create )

	return obj;
}

//
// Регистраторы фабрик для встроенных типов ObjESSty-stdsn
//

oess_1::stdsn::factory_registrator_t
oess_1::stdsn::shptr_t::oess_serializer_t::m_factory_reg(
	"oess_1::stdsn::shptr_t",
	&oess_1::stdsn::shptr_t::oess_serializer_t::factory );

} /* namespace stdsn */

} /* namespace oess_1 */

