//
// LDASTools AL - A library collection to provide an abstraction layer
//
// Copyright (C) 2018 California Institute of Technology
//
// LDASTools AL is free software; you may redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 (GPLv2) of the
// License or at your discretion, any later version.
//
// LDASTools AL is distributed in the hope that it will be useful, but
// without any warranty or even the implied warranty of merchantability
// or fitness for a particular purpose. See the GNU General Public
// License (GPLv2) for more details.
//
// Neither the names of the California Institute of Technology (Caltech),
// The Massachusetts Institute of Technology (M.I.T), The Laser
// Interferometer Gravitational-Wave Observatory (LIGO), nor the names
// of its contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// You should have received a copy of the licensing terms for this
// software included in the file LICENSE located in the top-level
// directory of this package. If you did not, you can view a copy at
// http://dcc.ligo.org/M1500244/LICENSE
//

#ifndef GENERAL__MUTEXLOCK_BATON_CC
#define GENERAL__MUTEXLOCK_BATON_CC

#include <pthread.h>

#include <cassert>

#include <sstream>

#include "ldastoolsal/AtExit.hh"

namespace LDASTools
{
    namespace AL
    {
        class MutexLock::baton_type::impl
        {
        private:
            impl( impl const& );
            impl& operator=( impl const& );

        public:
            typedef pthread_mutex_t mutex_type;

            bool       logging;
            mutex_type mutex;

            inline impl( bool Logging ) : logging( Logging )
            {
                error(
                    pthread_mutex_init(
                        ref( ), static_cast< pthread_mutexattr_t* >( NULL ) ),
                    "MutexLock::baton_type::ctor" );
            }

            inline ~impl( )
            {
                //-----------------------------------------------------------------
                // Ensure the resource is ready to be recovered.
                //-----------------------------------------------------------------
                const int status = pthread_mutex_destroy( ref( ) );

#if 0
	if ( ! ( ( status == EBUSY )
		 && ( LDAS::AtExit::IsExiting( ) ) ) )
	{
	  //---------------------------------------------------------------
	  // Most of the time check for the error.
	  //   Only when the system is exiting and the error is EBUSY
	  //   is the error quietly ignored.
	  //---------------------------------------------------------------
	  error( status, "MutexLock::baton_type::dtor" );
	}
#else
                if ( status != EBUSY )
                {
                    //---------------------------------------------------------------
                    // Most of the time check for the error.
                    //   Only when the system is exiting and the error is EBUSY
                    //   is the error quietly ignored.
                    //---------------------------------------------------------------
                    error( status, "MutexLock::baton_type::dtor" );
                }
#endif
            }

            inline bool
            Logging( ) const
            {
                return logging;
            }

            inline void
            lock( )
            {
                error( pthread_mutex_lock( ref( ) ),
                       "MutexLock::baton_type::lock" );
            }

            inline mutex_type*
            ref( )
            {
                return &mutex;
            }

            inline void
            trylock( )
            {
                error( pthread_mutex_trylock( ref( ) ),
                       "MutexLock::baton_type::trylock" );
            }

            inline void
            unlock( )
            {
                error( pthread_mutex_unlock( ref( ) ),
                       "MutexLock::baton_type::unlock" );
            }

        private:
            inline void
            error( int Code, const char* Action )
            {
                switch ( Code )
                {
                case 0:
                    break;
                case EBUSY:
                    // Already locked
                    throw MutexLock::BusyError( );
                    break;
                default:
                {
                    std::ostringstream msg;

                    msg << Action << ": " << strerror( Code );
                    throw std::runtime_error( msg.str( ) );
                }
                break;
                }
            }
        };
    } // namespace AL
} // namespace LDASTools

#endif /* GENERAL__MUTEXLOCK_BATON_CC */
