/*
 * 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 <limits.h>
#include "daemon/ProfileComponentsHolder.h"
#include "treemanager/IMOTreeManager.h"
#include "serverexchange/IServerExchangeManager.h"
#include "serverexchange/commands/ServerPollingInfoCommand.h"
#include "Utils.h"
#include <Logger/LoggerMacroses.h>

const char* const c_LogName = "ServerPollingInfoCommand";

using namespace NS_DM_Client;
using namespace NS_DM_Client::NS_Communication;


ServerPollingInfoCommand::ServerPollingInfoCommand(ProfileComponentsHolder *pHolder,
                                                   String &uriPSupported,
                                                   String &uriPInterval,
                                                   String &uriPAttempts) :
    m_pProfileHolder(pHolder),
    m_URIPSupported(uriPSupported),
    m_URIPInterval(uriPInterval),
    m_URIPAttempts(uriPAttempts)
{
}


ServerPollingInfoCommand::~ServerPollingInfoCommand()
{
}


bool ServerPollingInfoCommand::Execute()
{
GDLDEBUG("Enter");

    String result;

    bool pollingSupported = false;
    int  pollingInterval = 0; // seconds
    int  pollingAttempts = 0;

    if (e_Ok == m_pProfileHolder->GetMOTreeManager()->GetValue(m_URIPSupported, result, NULL))
    {
        pollingSupported = IsBooleanTrue(result);
    }

    if (e_Ok == m_pProfileHolder->GetMOTreeManager()->GetValue(m_URIPInterval , result, NULL))
    {
        pollingInterval = atoi(result.c_str());
        if (pollingInterval == INT_MAX || pollingInterval == INT_MIN)
        {
            pollingInterval = 0;
        }
    }

    if (e_Ok == m_pProfileHolder->GetMOTreeManager()->GetValue(m_URIPAttempts, result, NULL))
    {
        pollingAttempts = atoi(result.c_str());
        if (pollingAttempts == INT_MAX || pollingAttempts == INT_MIN)
        {
            pollingAttempts = 0;
        }
    }

    m_pProfileHolder->GetServerExchangeManager()->SetServerPollerInfo(pollingSupported, pollingInterval, pollingAttempts);

GDLDEBUG("Leave");

    return true;
}

