/*
 * Copyright 2009 Funambol, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/* $Id$ */

#include "commontypes.h"
#include "lock.h"
#include "serverexchange/MessageProcessingState.h"

using namespace NS_DM_Client::NS_Common;
using namespace NS_DM_Client::NS_Communication;


MessageProcessingState::MessageProcessingState() : m_cmdCount(0)
{
}


MessageProcessingState::~MessageProcessingState()
{
}


void MessageProcessingState::SetCommandsCount(unsigned int cmdCount)
{
    Lock lock(m_csProcState);
    m_cmdCount = cmdCount;
    if (0 == m_cmdCount)
        m_condNoCommands.Signal();
}


void MessageProcessingState::DecCommandsCount()
{
    Lock lock(m_csProcState);
    if (m_cmdCount)
        m_cmdCount--;

    if (0 == m_cmdCount)
        m_condNoCommands.Signal();
}


void MessageProcessingState::DecCommandsCount(unsigned int count)
{
    Lock lock(m_csProcState);
    if (m_cmdCount)
        m_cmdCount -= count;

    if (0 == m_cmdCount)
        m_condNoCommands.Signal();
}


unsigned int MessageProcessingState::GetCommandsCount()
{
    Lock lock(m_csProcState);
    return m_cmdCount;
}


void MessageProcessingState::IncCommandsCount(unsigned int delta)
{
    Lock lock(m_csProcState);
    m_cmdCount += delta;
}


bool MessageProcessingState::HasAllCommandsProcessed()
{
    Lock lock(m_csProcState);
    return 0 == m_cmdCount;
}


void MessageProcessingState::Wait()
{
    Lock lock(m_csProcState);
    if (m_cmdCount)
        m_condNoCommands.Wait(m_csProcState);
}
