/*

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
*/

#include <cerrno>
#include <cstring>

#include <sys/types.h>
#include <sys/stat.h>

#ifndef __unix__
#include <io.h>
#else
#include <unistd.h>
#endif

#include <ace/OS.h>

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

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

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

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

using namespace std;

namespace oess_1 {

namespace file {

const int	c_invalid_file = -1;
const size_t	c_buf_size = 4096;

//
// file_t
//

file_t::file_t() :
	m_file( c_invalid_file ),
	m_is_read_only( false )
{
	m_buf.set( new oess_1::char_t[ c_buf_size ], c_buf_size );
}

file_t::~file_t()
{
	close();
}

void
file_t::open(
	const std::string & file_name,
	bool is_read_only )
{
	if( c_invalid_file != m_file )
		OESS_THROW_LOGIC( oess_1::file::err::c_file_open,
			"file is already open" )

	m_file = impl::open_and_lock( file_name.c_str(), is_read_only );
	m_is_read_only = is_read_only;
}

void
file_t::create(
	const std::string & file_name )
{
	if( c_invalid_file != m_file )
		OESS_THROW_LOGIC( oess_1::file::err::c_file_open,
			file_name << ": file is already open" )

	m_file = impl::create_and_lock( file_name.c_str() );
	m_is_read_only = false;
}

void
file_t::close()
{
	try {
		if( c_invalid_file != m_file ) {
			impl::unlock_and_close( m_file );
		}
	}
	catch( oess_1::ex_t & x ) {
		OESS_1_LOG_ERR( x.query_err_code() << std::endl )
	}
	catch( ... ) {
	}

	m_file = c_invalid_file;
}

oess_1::uint_t
file_t::tell()
{
	is_workable( true );

	long v = ::lseek( m_file, 0, SEEK_CUR );
	if( v < 0 )
		OESS_THROW_PHYSIC( oess_1::file::err::c_unexpected,
			"lseek fail: errno: " << errno
			<< ", strerror: " << strerror( errno ) )

	return (oess_1::uint_t) v;
}

void
file_t::seek( oess_1::uint_t pos )
{
	is_workable( true );

	if( ::lseek( m_file, pos, SEEK_SET ) < 0 )
		OESS_THROW_PHYSIC( oess_1::file::err::c_unexpected,
			"seek fail: errno: " << errno
			<< ", strerror: " << strerror( errno ) )
}

oess_1::uint_t
file_t::length()
{
	is_workable( true );

	oess_1::uint_t cur = tell();
	long length = ::lseek( m_file, 0, SEEK_END );
	if( length < 0 )
		OESS_THROW_PHYSIC( oess_1::file::err::c_unexpected,
			"seek fail: errno: " << errno
			<< ", strerror: " << strerror( errno ) )

	seek( cur );

	return (oess_1::uint_t) length;
}

bool
file_t::eof() const
{
	file_t * f = const_cast< file_t * >( this );
	return ( f->tell() == f->length() );
}

void
file_t::chsize(
	oess_1::uint_t size )
{
	is_workable( false );

	impl::truncate_file( m_file, size );
}

void
file_t::remove( const std::string & file_name )
{
	impl::remove_file( file_name.c_str() );
}

bool
file_t::is_file_exists(
	const std::string & file_name )
{
	return impl::is_file_exists( file_name.c_str() );
}

void
file_t::rename_file(
	const std::string & what,
	const std::string & to,
	bool auto_destroy_existing_target )
	{
		if( is_file_exists( to ) )
			if( auto_destroy_existing_target )
				remove( to );
			else
				OESS_THROW_LOGIC( err::c_target_already_exists,
					"unable to rename '" << what << "' to '"
					<< to << "'. Target file already exists" )

		if( rename( what.c_str(), to.c_str() ) )
			OESS_THROW_PHYSIC( err::c_rename_fail,
				"unable to rename '" << what << "' to '"
				<< to << "'. errno == " << errno
				<< ", strerror: " << strerror( errno ) )
	}

const oess_1::char_t *
file_t::in_reserve(
	size_t item_count,
	size_t item_size,
	size_t & item_available )
{
	is_workable( true );

	// Определяем количество байт, которое необходимо
	// загрузить.
	size_t bytes_to_read = item_count * item_size;
	if( bytes_to_read > m_buf.size() )
		bytes_to_read = m_buf.size();

	// Выравняем это количество на размер элемента.
	item_available = bytes_to_read / item_size;
	bytes_to_read = item_available * item_size;

	// Загрузим содержимое из файла.
	int bytes_read = ::read( m_file, m_buf.query(), bytes_to_read );
	if( bytes_read != (int)bytes_to_read )
		OESS_THROW_PHYSIC( oess_1::file::err::c_read_fail,
			"bytes to read: " << bytes_to_read
			<< ", bytes read: " << bytes_read
			<< ", position: " << tell()
			<< ", errno: " << ACE_OS::last_error()
			<< ", strerror: " << ACE_OS::strerror( ACE_OS::last_error() ) )

	return m_buf.query();
}

void
file_t::in_shift(
	size_t item_count,
	size_t item_size )
{
	// Ничего не делаем.
}

oess_1::char_t *
file_t::out_reserve(
	size_t item_count,
	size_t item_size,
	size_t & item_available )
{
	is_workable( false );

	// Определяем количество байт, которое может
	// поместиться во внутренний буфер.
	size_t bytes_to_read = item_count * item_size;
	if( bytes_to_read > m_buf.size() )
		bytes_to_read = m_buf.size();

	// Выравняем это количество на размер элемента.
	item_available = bytes_to_read / item_size;
	bytes_to_read = item_available * item_size;

	return m_buf.query();
}

void
file_t::out_shift(
	size_t item_count,
	size_t item_size )
{
	size_t bytes_to_write = item_count * item_size;

	// Записываем содержимое в файл.
	int bytes_wrote = ::write( m_file, m_buf.query(), bytes_to_write );
	if( bytes_wrote != (int)bytes_to_write )
		OESS_THROW_PHYSIC( oess_1::file::err::c_write_fail,
			"bytes to write: " << bytes_to_write
			<< ", bytes wrote: " << bytes_wrote )

}

void
file_t::is_workable( bool is_read_only_op ) const
{
	if( c_invalid_file == m_file )
		OESS_THROW_LOGIC( oess_1::file::err::c_file_not_open, "" )

	if( m_is_read_only && !is_read_only_op )
		OESS_THROW_LOGIC( oess_1::file::err::c_read_only_mode, "" )
}

} /* namespace file */

} /* namespace oess_1 */
