#include "bu/debugmutex.h"

#include "bu/exceptionbase.h"

Bu::DebugMutex::DebugMutex()
{
}

Bu::DebugMutex::~DebugMutex()
{
}

int Bu::DebugMutex::lock()
{
    pthread_t self = pthread_self();
    mState.lock();
    bool bFound = false;
    for( ThreadList::iterator i = lThreads.begin(); i; i++ )
    {
        if( (*i) == self )
        {
            bFound = true;
            if( (*i).bLocked == true )
            {
                throw Bu::ExceptionBase( Bu::String("Double lock in thread: %1").arg( (*i).sName ).end().getStr() );

            }
            else
            {
                (*i).bLocked = true;
            }
            break;
        }
    }
    if( bFound == false )
    {
        lThreads.append( ThreadInfo( true ) );
    }
    mState.unlock();
    return Bu::Mutex::lock();
}

int Bu::DebugMutex::unlock()
{
    pthread_t self = pthread_self();
    mState.lock();
    bool bFound = false;
    for( ThreadList::iterator i = lThreads.begin(); i; i++ )
    {
        if( (*i) == self )
        {
            bFound = true;
            if( (*i).bLocked == false )
            {
                throw Bu::ExceptionBase( Bu::String("Unlock in thread that did not lock: %1").arg( (*i).sName ).end().getStr() );

            }
            else
            {
                (*i).bLocked = false;
            }
            break;
        }
    }
    if( bFound == false )
    {
        ThreadInfo info( false );
        throw Bu::ExceptionBase( Bu::String("Unlock in thread that never locked mutex: %1").arg( info.sName ).end().getStr() );
    }
    mState.unlock();
    return Bu::Mutex::unlock();
}

int Bu::DebugMutex::trylock()
{
    return Bu::Mutex::trylock();
}

