/*
 * 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 "lock.h"
#include "common/SyncCall.h"
#include "daemon/ProfileComponentsHolder.h"
#include "executionqueue/IExecutionQueue.h"
#include <Logger/LoggerMacroses.h>

const char* const c_LogName = "SyncCall";

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


SyncCall::SyncCall(NS_DM_Client::ICommand* pCommand, NS_DM_Client::ProfileComponentsHolder *pProfile, bool isClearCommand) :
    m_pCommand(pCommand),
    m_pProfileHolder(pProfile),
    m_isClearCommand(isClearCommand)
{
}


SyncCall::~SyncCall()
{
    if (m_isClearCommand && m_pCommand)
    {
        delete m_pCommand;
        m_pCommand = NULL;
    }
}


void SyncCall::Call()
{
GDLDEBUG("Enter");

    Lock lock(m_critSection);

    if (m_pCommand && m_pProfileHolder)
    {
        IExecutionQueue *pExeQueue = m_pProfileHolder->GetExecutionQueue();
        if(pExeQueue == NULL)
        {
            GDLERROR("pExeQueue is NULL");
            return;
        }

        GDLDEBUG("m_pCommand is %p",m_pCommand);
        if (!pExeQueue->Add(*m_pCommand))
        {
            delete m_pCommand;
            m_pCommand = NULL;
        }

        m_condition.Wait(m_critSection);
    }

GDLDEBUG("Leave");
}


void SyncCall::Notify()
{
GDLDEBUG("Enter");

    Lock lock(m_critSection);

    m_condition.Signal();

GDLDEBUG("Leave");
}
