/*
 * 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 "executionqueue/CommandInvokeThread.h"
#include "executionqueue/ICommand.h"
#include "Event.h"

using namespace NS_DM_Client;
using namespace NS_DM_Client::NS_ExecutionQueue;
using namespace NS_DM_Client::NS_Common;

CommandInvokeThread::CommandInvokeThread(
    EventEx&      resEvent,
    CommandsQueue&  cmdsQ,
    NS_Logging::Logger& logger
):
    m_resumeEvent(resEvent),
    m_cmdsQ(cmdsQ),
    m_logger(logger)
{
LOG_DEBUG_(m_logger,"Enter");

    terminate = false;

LOG_DEBUG_(m_logger,"Leave");
}


CommandInvokeThread::~CommandInvokeThread(void)
{
LOG_DEBUG_(m_logger,"Enter");
LOG_DEBUG_(m_logger,"Leave");
}


void CommandInvokeThread::run()
{
LOG_DEBUG_(m_logger,"Enter");

    LOG_DEBUG_(m_logger, "CommandInvokeThread::run (%p) started with CmdsQ (%p). ", this, &m_cmdsQ);

    while(!terminate)
    {
        EnumResumeReason resumeReason = static_cast<EnumResumeReason>(m_resumeEvent.wait());
        if (resumeReason == e_Stop)
        {
            LOG_DEBUG_(m_logger, "CommandInvokeThread::run STOP signal. ");
            break;
        }
        else if (resumeReason == e_NewCommand)
        {
            LOG_DEBUG_(m_logger, "CommandInvokeThread::run NEWCOMMAND signal. ");
            ICommand* cmd = (ICommand*)NULL;
            while (!terminate && (cmd = m_cmdsQ.popCommand()) != (ICommand*)NULL)
            {
                LOG_DEBUG_(m_logger, "Command (%p) started. ", cmd);
                bool cmdRes = cmd->Execute();
                LOG_DEBUG_(m_logger, "Command (%p) finished with result=%d. ", cmd, cmdRes);
                delete cmd;
            }
        }
        else
        {
            LOG_ERROR_(m_logger, "Unkown Event: %d", resumeReason);
        }
    }
    terminate = false;

    LOG_DEBUG_(m_logger, "CommandInvokeThread::run (%p) finished. ", this);

LOG_DEBUG_(m_logger,"Leave");
}


void CommandInvokeThread::softTerminate()
{
LOG_DEBUG_(m_logger,"Enter");

    LOG_DEBUG_(m_logger, "CommandInvokeThread: issue STOP signal. ");
//    FThread::softTerminate();
    Thread::softTerminate();
    m_resumeEvent.signal(e_Stop);

LOG_DEBUG_(m_logger,"Leave");
}
