/*
    libmaus2
    Copyright (C) 2009-2013 German Tischler
    Copyright (C) 2011-2013 Genome Research Limited

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#if ! defined(LIBMAUS2_AIO_POSIXFDINPUTOUTPUTSTREAMBUFFER_HPP)
#define LIBMAUS2_AIO_POSIXFDINPUTOUTPUTSTREAMBUFFER_HPP

#include <ostream>

#include <libmaus2/LibMausConfig.hpp>
#include <libmaus2/posix/PosixFunctions.hpp>
#include <libmaus2/autoarray/AutoArray.hpp>
#include <libmaus2/aio/PosixFdInput.hpp>

namespace libmaus2
{
	namespace aio
	{
		struct PosixFdInputOutputStreamBuffer : public ::std::streambuf
		{
			private:
			// get default block size
			static uint64_t getDefaultBlockSize()
			{
				return 64*1024;
			}

			// get optimal i/o block size
			static int64_t getOptimalIOBlockSize(int const fd, std::string const & fn)
			{
				int64_t const fsopt = libmaus2::aio::PosixFdInput::getOptimalIOBlockSize(fd,fn);

				if ( fsopt <= 0 )
					return getDefaultBlockSize();
				else
					return fsopt;
			}

			// file descriptor
			int fd;
			// close file at deconstruction if true
			bool closefd;
			// optimal block size for file system
			int64_t const optblocksize;
			// size of buffer
			uint64_t const buffersize;
			// buffer
			::libmaus2::autoarray::AutoArray<char> buffer;

			// read position
			uint64_t readpos;
			// write position
			uint64_t writepos;

			// open the file
			int doOpen(std::string const & filename, std::ios_base::openmode const cxxmode)
			{
				if ( (cxxmode & std::ios::app) )
				{
					libmaus2::exception::LibMausException lme;
					lme.getStream() << "libmaus2::aio::PosixFdInputOutputStreamBuffer::doOpen(): std::ios::app flag not supported" << std::endl;
					lme.finish();
					throw lme;
				}
				if ( (cxxmode & std::ios::ate) )
				{
					libmaus2::exception::LibMausException lme;
					lme.getStream() << "libmaus2::aio::PosixFdInputOutputStreamBuffer::doOpen(): std::ios::ate flag not supported" << std::endl;
					lme.finish();
					throw lme;
				}
				if ( ! ((cxxmode & std::ios::in) && (cxxmode & std::ios::out)) )
				{
					libmaus2::exception::LibMausException lme;
					lme.getStream() << "libmaus2::aio::PosixFdInputOutputStreamBuffer::doOpen(): std::ios::in or std::ios::out not set " << std::endl;
					lme.finish();
					throw lme;
				}

				int mode = libmaus2::posix::PosixFunctions::get_O_RDWR() | libmaus2::posix::PosixFunctions::get_O_CREAT();

				// truncate if requested
				if ( (cxxmode & std::ios::trunc) )
				{
					mode |= libmaus2::posix::PosixFunctions::get_O_TRUNC();
				}

				int fd = -1;

				libmaus2::autoarray::AutoArray<unsigned char> Amode(libmaus2::posix::PosixFunctions::getOpenModeSize());
				libmaus2::posix::PosixFunctions::encode(0644,Amode.begin(),Amode.size());

				while ( (fd = libmaus2::posix::PosixFunctions::open(filename.c_str(),mode,Amode.begin())) < 0 )
				{
					int const error = errno;

					switch ( error )
					{
						case EINTR:
						case EAGAIN:
							break;
						default:
						{
							libmaus2::exception::LibMausException se;
							se.getStream() << "PosixInputOutputStreamBuffer::doOpen(): open("<<filename<< "," << mode << ") failed: " << strerror(error) << std::endl;
							se.finish();
							throw se;
						}
					}
				}

				return fd;
			}

			// close the file descriptor
			void doClose()
			{
				while ( close(fd) < 0 )
				{
					int const error = errno;

					switch ( error )
					{
						case EINTR:
						case EAGAIN:
							break;
						default:
						{
							libmaus2::exception::LibMausException se;
							se.getStream() << "PosixInputOutputStreamBuffer::doClose(): close() failed: " << strerror(error) << std::endl;
							se.finish();
							throw se;
						}
					}
				}
			}

			// flush the file
			void doFlush()
			{
				#if defined(LIBMAUS2_HAVE_FSYNC)
				while ( libmaus2::posix::PosixFunctions::fsync(fd) < 0 )
				{
					int const error = errno;

					switch ( error )
					{
						case EINTR:
						case EAGAIN:
							break;
						case EROFS:
						case EINVAL:
							// descriptor does not support flushing
							return;
						default:
						{
							libmaus2::exception::LibMausException se;
							se.getStream() << "PosixInputOutputStreamBuffer::doSync(): fsync() failed: " << strerror(error) << std::endl;
							se.finish();
							throw se;
						}
					}
				}
				#endif
			}


			// seek
			libmaus2::off_t doSeek(int64_t const p, int const whence)
			{
				libmaus2::autoarray::AutoArray<unsigned char> Aoffin(libmaus2::posix::PosixFunctions::getOffTSize());
				libmaus2::autoarray::AutoArray<unsigned char> Aoffout(libmaus2::posix::PosixFunctions::getOffTSize());
				libmaus2::autoarray::AutoArray<unsigned char> Aoffin64(sizeof(libmaus2::off_t));

				// encode to 64 bit array
				libmaus2::posix::PosixFunctions::encodeSigned<libmaus2::off_t>(p,Aoffin64.begin(),sizeof(libmaus2::off_t));
				// translate to off_t
				libmaus2::posix::PosixFunctions::translateSigned(Aoffin.begin(),Aoffin.size(),Aoffin64.begin(),Aoffin64.size());

				// translate back
				libmaus2::posix::PosixFunctions::translateSigned(Aoffin64.begin(),Aoffin64.size(),Aoffin.begin(),Aoffin.size());
				// check
				assert ( libmaus2::posix::PosixFunctions::decodeSigned<libmaus2::off_t>(Aoffin64.begin(),Aoffin64.size()) == p );

				while ( true )
				{
					libmaus2::posix::PosixFunctions::posix_lseek(Aoffout.begin(),fd,Aoffin.begin(),whence);

					if ( libmaus2::posix::PosixFunctions::offTIsMinusOne(Aoffout.begin()) )
					{
						int const error = errno;

						switch ( error )
						{
							case EINTR:
							case EAGAIN:
								// try again
								break;
							default:
							{
								libmaus2::exception::LibMausException se;
								se.getStream() << "PosixInputOutputStreamBuffer::doSeek(): seek() failed: " << strerror(error) << std::endl;
								se.finish();
								throw se;
							}
						}
					}
					else
					{
						return libmaus2::posix::PosixFunctions::decodeSigned<libmaus2::off_t>(Aoffout.begin(),Aoffout.size());
					}
				}
			}

			// write buffer contents
			void doSync()
			{
				uint64_t n = pptr()-pbase();
				pbump(-n);

				char * p = pbase();

				while ( n )
				{
					::libmaus2::ssize_t const w = ::libmaus2::posix::PosixFunctions::write(fd,p,n);

					if ( w < 0 )
					{
						int const error = errno;

						switch ( error )
						{
							case EINTR:
							case EAGAIN:
								break;
							default:
							{
								libmaus2::exception::LibMausException se;
								se.getStream() << "PosixInputOutputStreamBuffer::doSync(): write() failed: " << strerror(error) << std::endl;
								se.finish();
								throw se;
							}
						}
					}
					else
					{
						assert ( w <= static_cast<int64_t>(n) );
						n -= w;
						writepos += w;
					}
				}

				assert ( ! n );
			}

			size_t doRead(char * buffer, size_t count)
			{
				::libmaus2::ssize_t r = -1;

				while ( (r=::libmaus2::posix::PosixFunctions::read(fd,buffer,count)) < 0 )
				{
					int const error = errno;

					switch ( error )
					{
						case EINTR:
						case EAGAIN:
							// try again
							break;
						default:
						{
							libmaus2::exception::LibMausException se;
							se.getStream() << "PosixInputOutputStreamBuffer::doRead(): read() failed: " << strerror(error) << std::endl;
							se.finish();
							throw se;
						}
					}
				}

				return r;
			}

			// gptr as unsigned pointer
			uint8_t const * uptr() const
			{
				return reinterpret_cast<uint8_t const *>(gptr());
			}

			void checkWriteBuffer()
			{
				// if write buffer is not empty, then flush it
				if ( pptr() != pbase() )
				{
					doSync();

					// get write position
					assert ( static_cast<libmaus2::off_t>(writepos) == doSeek(0,libmaus2::posix::PosixFunctions::get_SEEK_CUR()) );
				}
			}

			public:
			PosixFdInputOutputStreamBuffer(int const rfd, int64_t const rbuffersize)
			: fd(rfd),
			  closefd(false),
			  optblocksize((rbuffersize < 0) ? getOptimalIOBlockSize(fd,std::string()) : rbuffersize),
			  buffersize(optblocksize),
			  buffer(buffersize,false),
			  readpos(0),
			  writepos(0)
			{
				setg(buffer.end(),buffer.end(),buffer.end());
				setp(buffer.begin(),buffer.end()-1);
			}

			PosixFdInputOutputStreamBuffer(std::string const & fn, std::ios_base::openmode const cxxmode, int64_t const rbuffersize)
			:
			  fd(doOpen(fn,cxxmode)),
			  closefd(true),
			  optblocksize((rbuffersize < 0) ? getOptimalIOBlockSize(fd,fn) : rbuffersize),
			  buffersize(optblocksize),
			  buffer(buffersize,false),
			  readpos(0),
			  writepos(0)
			{
				// empty get buffer
				setg(buffer.end(),buffer.end(),buffer.end());
				// empty put buffer
				setp(buffer.begin(),buffer.end()-1);
			}

			~PosixFdInputOutputStreamBuffer()
			{
				sync();
				if ( closefd )
					doClose();
			}

			int sync()
			{
				// write any data in the put buffer
				doSync();
				// flush file
				doFlush();
				return 0; // no error, -1 for error
			}

			int_type underflow()
			{
				// if there is still data, then return it
				if ( gptr() < egptr() )
					return static_cast<int_type>(*uptr());

				assert ( gptr() == egptr() );

				// load data
				size_t const g = doRead(buffer.begin(),buffersize);

				// set buffer pointers
				setg(buffer.begin(),buffer.begin(),buffer.begin()+g);

				// update end of buffer position
				readpos += g;

				if ( g )
					return static_cast<int_type>(*uptr());
				else
					return traits_type::eof();
			}

			int_type overflow(int_type c = traits_type::eof())
			{
				if ( c != traits_type::eof() )
				{
					*pptr() = c;
					pbump(1);
					doSync();
				}

				return c;
			}

			/**
			 * seek to absolute position
			 **/
			::std::streampos seekpos(::std::streampos sp, ::std::ios_base::openmode /* which */)
			{
				// flush write buffer before seeking anywhere
				checkWriteBuffer();
				// seek
				libmaus2::off_t const off = doSeek(sp,libmaus2::posix::PosixFunctions::get_SEEK_SET());

				if ( off == static_cast<libmaus2::off_t>(-1) )
					return -1;

				// empty get buffer
				setg(buffer.end(),buffer.end(),buffer.end());
				// empty put buffer
				setp(buffer.begin(),buffer.end()-1);
				// set positions
				readpos = off;
				writepos = off;

				return off;
			}

			/**
			 * relative seek
			 **/
			::std::streampos seekoff(::std::streamoff off, ::std::ios_base::seekdir way, ::std::ios_base::openmode which)
			{
				// absolute seek
				if ( way == ::std::ios_base::beg )
				{
					return seekpos(off,which);
				}
				// seek relative to current position
				else if ( way == ::std::ios_base::cur )
				{
					if ( which == std::ios_base::in )
					{
						int64_t const bufpart = egptr() - eback();
						assert ( static_cast<int64_t>(readpos) >= bufpart );
						return seekpos((readpos - bufpart) + (gptr()-eback()) + off,which);
					}
					else if ( which == std::ios_base::out )
					{
						return seekpos(writepos + (pptr()-pbase()) + off,which);
					}
					else
					{
						return -1;
					}
				}
				// seek relative to end of file
				else if ( way == ::std::ios_base::end )
				{
					libmaus2::off_t const curoff = doSeek(0, libmaus2::posix::PosixFunctions::get_SEEK_CUR());
					libmaus2::off_t const endoff = doSeek(0, libmaus2::posix::PosixFunctions::get_SEEK_END());
					libmaus2::off_t const curag = doSeek(curoff,libmaus2::posix::PosixFunctions::get_SEEK_SET());

					if ( curag != curoff )
						return -1;

					if ( endoff == static_cast<libmaus2::off_t>(-1) )
						return -1;

					return seekpos(endoff+off,which);
				}
				else
				{
					return -1;
				}
			}
		};
	}
}
#endif
