/*
 * 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 "serverexchange/ServerPoller.h"
#include "executionqueue/IExecutionQueue.h"
#include "serverexchange/commands/ClientSessionCommand.h"
#include "Logger/LoggerMacroses.h"

using namespace NS_DM_Client;
using namespace NS_DM_Client::NS_Communication;

static const char * c_LogName = "ServerPoller";

ServerPoller::ServerPoller()
{
}


ServerPoller::~ServerPoller()
{
    GDLDEBUG("ENTER >> destroying %p", this);
    m_timer.Stop();
    GDLDEBUG("LEAVE << destroying");
}


void ServerPoller::Call()
{
    GDLDEBUG("Request to start client initiated session");

    ICommand *cmd = new(std::nothrow) NS_Communication::ClientSessionCommand(*m_pProfile->GetServerExchangeManager());
    if (cmd != (ICommand*)NULL)
    {
        if (!m_pProfile->GetExecutionQueue()->Add(*cmd))
        {
            delete cmd;
        }
    }
    else
    {
        GDLERROR("Pointer to ClientSessionCommand is NULL");
    }

    GDLDEBUG("LEAVE");
}


void ServerPoller::Start()
{
    GDLDEBUG("ENTER");
    m_timer.SetCallback(this);
    m_timer.Start();
    GDLDEBUG("LEAVE");
}


void ServerPoller::Stop()
{
    GDLDEBUG("ENTER");
    m_timer.Stop();
    GDLDEBUG("LEAVE");
}


void ServerPoller::SetPollingInterval(int t)
{
    m_timer.SetInterval(t);
}


void ServerPoller::SetPollingAttempts(int count)
{
    m_timer.SetTicksCount(count);
}


void ServerPoller::SetProfile(ProfileComponentsHolder &profile)
{
    m_pProfile = &profile;
}
