/*

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.

*/

/*!
	\since v.1.4.0
	\brief Стандартная реализация интерфейса %snapshot_collection_t.
*/

#include <oess_1/db/storage/trx/h/std_snapshot_collection.hpp>

#include <vector>

#include <ace/OS.h>

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

#include <oess_1/file/h/file.hpp>

#include <oess_1/db/storage/h/errno.hpp>

#include <oess_1/db/storage/trx/h/find_all_trace_files.hpp>

namespace oess_1 {

namespace db {

namespace storage {

namespace trx {

//
// std_snapshot_collection_t
//

std_snapshot_collection_t::std_snapshot_collection_t(
	const std::string & physic_name )
	:	m_physic_name( physic_name )
	,	m_all_snapshot_numbers( find_all_snapshot_files( physic_name ) )
	{}

std_snapshot_collection_t::~std_snapshot_collection_t()
	{}

unsigned int
std_snapshot_collection_t::size() const
	{
		return m_all_snapshot_numbers.size();
	}

trace_file_number_set_t
std_snapshot_collection_t::non_actual() const
	{
		trace_file_number_set_t non_actual_numbers( m_all_snapshot_numbers );

		if( !non_actual_numbers.empty() )
			// Последний элемент множества является актуальным.
			non_actual_numbers.erase( *non_actual_numbers.rbegin() );

		return non_actual_numbers;
	}

trace_file_number_t
std_snapshot_collection_t::actual() const
	{
		// Актуальным является последний элемент множества.
		if( m_all_snapshot_numbers.empty() )
			OESS_THROW_LOGIC(
					oess_1::db::storage::err::c_no_actual_snapshot,
					"there is no actual snapshot for: " << m_physic_name );

		return *m_all_snapshot_numbers.rbegin();
	}

bool
std_snapshot_collection_t::has_actual() const
	{
		return ( !m_all_snapshot_numbers.empty() );
	}

void
std_snapshot_collection_t::include(
	const std::string & file_name,
	trace_file_number_t last_used_trace )
	{
		// Переименовываем временный файл под именем snapshot-файла
		// с использованием указанного максимального номера trace-файла.
		std::string new_snapshot_file_name = create_snapshot_file_name(
				m_physic_name, last_used_trace );

		oess_1::file::file_t::rename_file(
				file_name, new_snapshot_file_name );

		// Теперь осталось только включить новый файл в множество
		// номеров snapshot-файлов.
		m_all_snapshot_numbers.insert( last_used_trace );
	}

void
std_snapshot_collection_t::get_actual(
	const std::string & file_name ) const
	{
		// Выполняем перезапись указанного файла путем простого копирования
		// файла snapshot-а в указанный файл.
		std::string snapshot_file_name = create_snapshot_file_name(
				m_physic_name, actual() );

		oess_1::file::file_t snapshot_file;
		snapshot_file.open( snapshot_file_name, true );

		oess_1::file::file_t tmp_file;
		tmp_file.create( file_name );

		std::vector< char > buf( 4096 );

		oess_1::uint_t bytes_to_transfer = snapshot_file.length();
		while( bytes_to_transfer )
			{
				oess_1::uint_t portion_size = buf.capacity();
				if( portion_size > bytes_to_transfer )
					portion_size = bytes_to_transfer;

				snapshot_file.read( &buf[ 0 ], portion_size );
				tmp_file.write( &buf[ 0 ], portion_size );

				bytes_to_transfer -= portion_size;
			}
	}

void
std_snapshot_collection_t::destroy()
	{
		for( trace_file_number_set_t::iterator
				it = m_all_snapshot_numbers.begin(),
				it_end = m_all_snapshot_numbers.end();
				it != it_end; ++it )
			{
				oess_1::file::file_t::remove(
						create_snapshot_file_name( m_physic_name, *it ) );
			}

		m_all_snapshot_numbers.clear();
	}

//
// create_std_snapshot_collection
//

OESS_1__DB__FUNC(std::auto_ptr< snapshot_collection_t >)
create_std_snapshot_collection(
	const std::string & physic_name )
	{
		return std::auto_ptr< snapshot_collection_t >(
				new std_snapshot_collection_t( physic_name ) );
	}

} /* namespace trx */

} /* namespace storage */

} /* namespace db */

} /* namespace oess */

