/*
	Загрузка цепочки по указанному идентификатору из указанного хранилища.
*/

#include <iostream>
#include <list>
#include <set>
#include <stdexcept>

#include <cpp_util_2/h/lexcast.hpp>

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

#include <oess_1/io/h/mem_buf.hpp>

#include <oess_1/db/storage/h/chain_storage.hpp>
#include <oess_1/db/storage/h/page_index_calculator.hpp>

void
dump_buffer( const oess_1::io::mem_buf_t & b )
	{
		for( const oess_1::char_t * p = b.ptr(), * p_end = p + b.size();
				p != p_end; ++p)
			{
				char sz[ 32 ];
				std::sprintf( sz, "%02X ",
						static_cast< unsigned int >(
								static_cast< unsigned char >( *p ) ) );
				std::cout << sz;
			}
		std::cout << std::endl;
	}

void
do_open_and_load(
		const std::string & db_name,
		const oess_1::db::storage::chain_id_t & chain_id )
	{
		const oess_1::db::storage::config_t config;

		oess_1::io::mem_buf_t buf;
		oess_1::db::storage::chain_id_t first_chain;

		std::auto_ptr< oess_1::db::storage::chain_storage_t >
				storage( oess_1::db::storage::open_chain_storage(
						db_name,
						config,
						true,
						false,
						buf,
						oess_1::db::storage::no_chain_length_limit,
						first_chain ) );

		oess_1::io::mem_buf_t chain_value;
		storage->chain_load(
				chain_id,
				chain_value,
				oess_1::db::storage::no_chain_length_limit );

		dump_buffer( chain_value );
	}

int
main( int argc, char ** argv )
	{
		try
			{
				if( 3 != argc )
					{
						std::cerr << "test.storage.load_chain <db> <chain_id>"
								<< std::endl;
						return 1;
					}

				do_open_and_load(
						argv[ 1 ],
						cpp_util_2::lexcast<
								oess_1::db::storage::chain_id_t >( argv[ 2 ] ) );

				return 0;
			}
		catch( const std::exception & x )
			{
				std::cerr << x.what() << std::endl;
			}
		catch( ... )
			{
				std::cerr << "Unknown exception!" << std::endl;
			}

		return 2;
	}
