/*

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.

*/

/*!
	\file
	\since v.1.4.0
	\brief Класс %std_file_committer_t.
*/

#include <cpp_util_2/h/lexcast.hpp>
#include <cpp_util_2/lexcasts/h/util.hpp>

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

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

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

namespace oess_1 {

namespace db {

namespace storage {

namespace trx {

//
// std_file_committer_t
//

std_file_committer_t::std_file_committer_t(
	const std::string & physic_name )
	:	m_physic_name( physic_name )
	,	m_snapshots( create_std_snapshot_collection( physic_name ) )
	,	m_is_file_exists( false )
	,	m_page_size( 0 )
	{
		config_t config;
		m_result_file_name =	config.make_main_file_name( m_physic_name );
	}

std_file_committer_t::~std_file_committer_t()
	{
		if( m_is_file_exists )
			{
				try
					{
						m_file.close();
						oess_1::file::file_t::remove(
								make_tmp_file_name( m_physic_name ) );
					}
				catch( const std::exception & x )
					{
						OESS_1_LOG_ERR( x.what() << std::endl )
					}
				catch( ... )
					{}
			}
	}

void
std_file_committer_t::reduce_traces_set(
	const trace_file_number_set_t & all_traces,
	trace_file_number_set_t & actual_traces )
	{
		if( !m_snapshots->has_actual() )
			// Поскольку актуального snapshot-а нет, то результирующим
			// можеством должно стать исходное множество.
			actual_traces = all_traces;
		else
			{
				// Из исходного можества должны быть изъяты все элементы,
				// которые меньше или равны номеру актуального snapshot-а.
				trace_file_number_set_t::const_iterator upper_bound =
						all_traces.upper_bound( m_snapshots->actual() );
				if( upper_bound != all_traces.end() )
					{
						// Поскольку upper_bound может содержать номер
						// актуального snapshot-а, то нужно сделать дополнительные
						// действия перед копированием подмножества.
						if( m_snapshots->actual() == *upper_bound )
							++upper_bound;
						actual_traces.insert( upper_bound, all_traces.end() );
					}
			}
	}

void
std_file_committer_t::initialize(
	oess_1::uint_t total_page_count,
	oess_1::uint_t page_size,
	oess_1::uint_t block_size )
	{
		std::string tmp_file_name = make_tmp_file_name( m_physic_name );

		if( m_snapshots->has_actual() )
			{
				// В качестве начального содержимого временного файла
				// нужно брать значение актуального snapshot-а.
				m_snapshots->get_actual( tmp_file_name );
				m_file.open( tmp_file_name, false );

				// Уменьшаем общее число страниц, т.к. оно затем будет
				// использоваться для определения того, сколько пустых страниц
				// нужно добавить во временный файл.
				oess_1::uint_t existing_page_count = m_file.length() / page_size;
				if( existing_page_count > total_page_count )
					OESS_THROW_PHYSIC(
							oess_1::db::storage::err::c_db_page_count_mismatch,
							"physic_name: " << m_physic_name
							<< ", actual snapshot: " << m_snapshots->actual()
							<< ", snapshot page count: " << existing_page_count
							<< ", expected total page count: "
							<< total_page_count )

				total_page_count -= existing_page_count;
			}
		else
			{
				// Временный файл должен быть создан заново.
				m_file.create( tmp_file_name );
			}

		m_is_file_exists = true;
		m_page_size = page_size;
		m_io_buf.resize( page_size, 0 );

		// Нужно теперь забить весь файл нулями.
		const oess_1::uint_t portion_size = 100;
		std::vector< oess_1::char_t >	buf( portion_size * page_size, 0 );
		
		m_file.seek( m_file.length() );
		while( total_page_count )
			{
				oess_1::uint_t pages_to_write = portion_size;
				if( pages_to_write > total_page_count )
					pages_to_write = total_page_count;

				m_file.write( &buf[ 0 ], pages_to_write * page_size );

				total_page_count -= pages_to_write;
			}
	}

void
std_file_committer_t::finalize()
	{
		m_file.close();

		oess_1::file::file_t::rename_file(
				make_tmp_file_name( m_physic_name ),
				m_result_file_name,
				true );

		m_is_file_exists = false;
	}

bool
std_file_committer_t::is_insufficient_trace_info_allowed() const
	{
		return m_snapshots->has_actual();
	}

const std::string &
std_file_committer_t::physic_name() const
	{
		return m_physic_name;
	}

void
std_file_committer_t::set_result_file_name(
	const std::string & file_name )
	{
		m_result_file_name = file_name;
	}

void
std_file_committer_t::store_block(
	oess_1::uint_t ordinal,
	oess_1::uint_t block_index,
	const std::string & block_value )
	{
		m_file.seek( m_page_size * ordinal );
		m_file.read( &m_io_buf[ 0 ], m_page_size );

		std::copy( block_value.begin(), block_value.end(),
				&m_io_buf[ block_index * block_value.size() ] );

		m_file.seek( m_page_size * ordinal );
		m_file.write( &m_io_buf[ 0 ], m_page_size );
	}

std::string
std_file_committer_t::make_tmp_file_name(
	const std::string & physic_name )
	{
		return physic_name + ".replay";
	}

//
// unclear_file_committer_t
//

unclear_file_committer_t::unclear_file_committer_t(
	const std::string & physic_name )
	:	m_physic_name( physic_name )
	,	m_page_size( 0 )
	{
		config_t config;

		m_file.open( config.make_unclear_file_name( physic_name ), false );
	}

unclear_file_committer_t::~unclear_file_committer_t()
	{}

void
unclear_file_committer_t::reduce_traces_set(
	const trace_file_number_set_t & all_traces,
	trace_file_number_set_t & actual_traces )
	{
		if( 1 < all_traces.size() )
			OESS_THROW_PHYSIC(
					oess_1::db::storage::err::c_invalid_trace_mode,
					"unclear_file_committer_t cannot be used if trace file "
					"count greater than 1; traces count: " << all_traces.size() )

		actual_traces = all_traces;
	}

void
unclear_file_committer_t::initialize(
	oess_1::uint_t total_page_count,
	oess_1::uint_t page_size,
	oess_1::uint_t block_size )
	{
		m_page_size = page_size;
		m_io_buf.resize( page_size, 0 );

		// Если размер файла не совпадает с указанным размером,
		// то нужно добить остаток файла нулями.
		oess_1::uint_t required_file_size = total_page_count * page_size;
		oess_1::uint_t real_file_size = m_file.length();

		if( real_file_size < required_file_size )
			{
				// Нужно теперь забить хвост файла нулями.
				const oess_1::uint_t portion_size = 100;
				std::vector< oess_1::char_t >	buf(
						portion_size * page_size, 0 );

				oess_1::uint_t remaining = required_file_size - real_file_size;
				
				while( remaining )
					{
						oess_1::uint_t bytes_to_write = buf.size();
						if( bytes_to_write > remaining )
							bytes_to_write = remaining;
      
						m_file.write( &buf[ 0 ], bytes_to_write );
      
						remaining -= bytes_to_write;
					}
			}
	}

void
unclear_file_committer_t::finalize()
	{
		m_file.close();

		config_t config;
		oess_1::file::file_t::rename_file(
				config.make_unclear_file_name( m_physic_name ),
				config.make_main_file_name( m_physic_name ) );
	}

bool
unclear_file_committer_t::is_insufficient_trace_info_allowed() const
	{
		return true;
	}

void
unclear_file_committer_t::store_block(
	oess_1::uint_t ordinal,
	oess_1::uint_t block_index,
	const std::string & block_value )
	{
		m_file.seek( m_page_size * ordinal );
		m_file.read( &m_io_buf[ 0 ], m_page_size );

		std::copy( block_value.begin(), block_value.end(),
				&m_io_buf[ block_index * block_value.size() ] );

		m_file.seek( m_page_size * ordinal );
		m_file.write( &m_io_buf[ 0 ], m_page_size );
	}

//
// snapshot_file_committer_t
//

snapshot_file_committer_t::snapshot_file_committer_t(
	const std::string & physic_name )
	:	base_type_t( physic_name )
	{}

snapshot_file_committer_t::~snapshot_file_committer_t()
	{}

void
snapshot_file_committer_t::reduce_traces_set(
	const trace_file_number_set_t & all_traces,
	trace_file_number_set_t & actual_traces )
	{
		trace_file_number_set_t tmp_set( all_traces );
		if( tmp_set.size() > 1 )
			{
				// Последний файл не должен входить в snapshot.
				trace_file_number_t last = *tmp_set.rbegin();
				tmp_set.erase( last );

				// Все находящиеся в tmp_set trace-файлы можно будет считать
				// устаревшими после успешного формирования snapshot-а.
				m_outdated_traces = tmp_set;

				// Оставшийся в tmp_set последний элемент теперь будет
				// определять имя snapshot-файла.
				last = *tmp_set.rbegin();

				base_type_t::reduce_traces_set( tmp_set, actual_traces );

				// Если получили пустое множество, то создавать snapshot
				// файл не нужно. Это ситуация, когда snapshot с номером last
				// уже существует и является актуальным.
				if( actual_traces.empty() )
					OESS_THROW_LOGIC(
							oess_1::db::storage::err::c_no_traces_for_snapshot,
							"no traces beetwen actual snapshot and current "
							"trace file" )

				set_result_file_name(
						create_snapshot_file_name(
								physic_name(), last ) );
			}
		else
			OESS_THROW_LOGIC(
					oess_1::db::storage::err::c_no_traces_for_snapshot,
					"all_traces.size() == " << all_traces.size() )
	}

trace_file_number_set_t
snapshot_file_committer_t::outdated_traces() const
	{
		return m_outdated_traces;
	}

//
// create_std_file_committer
//

OESS_1__DB__FUNC(std::auto_ptr< committer_t >)
create_std_file_committer(
	const std::string & physic_name,
	trace_mode_t trace_mode )
	{
		if( trace_no == trace_mode )
			OESS_THROW_PHYSIC(
					oess_1::db::storage::err::c_trace_file_not_found,
					"storage cannot be repaired if trace_mode == trace_no" )

		if( trace_last == trace_mode )
			return std::auto_ptr< committer_t >(
					new unclear_file_committer_t( physic_name ) );
		
		return std::auto_ptr< committer_t >(
				new std_file_committer_t( physic_name ) );
	}

} /* namespace trx */

} /* namespace storage */

} /* namespace db */

} /* namespace oess */

