/*
 * 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 "common/commontypes.h"
#include "serverexchange/commands/AdjustFUMOStatus.h"
#include "daemon/ProfileComponentsHolder.h"
#include "Logger/LoggerMacroses.h"
#include "treemanager/IMOTreeManager.h"
#include "serverexchange/IServerExchangeManager.h"
#include "Utils.h"
#include <base/util/StringBuffer.h>


using namespace NS_DM_Client;
using namespace NS_DM_Client::NS_Communication;

static const char * const c_LogName = "AdjustFUMOStatus";

AdjustFUMOStatus::AdjustFUMOStatus(ProfileComponentsHolder *pHolder, String uriFUMO, uint value) :
    m_pProfileHolder(pHolder), m_uriFUMO(uriFUMO), m_value(value)
{
}

AdjustFUMOStatus::~AdjustFUMOStatus()
{
    m_pProfileHolder = NULL;
    GDLDEBUG("destroy AdjustFUMOStatus %x", this);
}

bool AdjustFUMOStatus::Execute()
{
    GDLDEBUG("State uri: %x", m_uriFUMO.c_str());
    Funambol::StringBuffer fmState(m_uriFUMO.c_str());
    GDLDEBUG("State uri: '%s'", fmState.c_str());

    if (m_uriFUMO[m_uriFUMO.size()] != '/')
    {
        fmState.append("/");
    }
    fmState.append("State");
    GDLDEBUG("State uri: '%s'", fmState.c_str());
    
    Funambol::Item item;
    Funambol::Target target(fmState.c_str());
    Funambol::Meta meta;
    meta.setType("text/plain");
    meta.setFormat("int");
    item.setTarget(&target);
    item.setMeta(&meta);
    
    char buffer[16];
    memset(buffer, '\0', 16);
    __sprintf(buffer, "%d", m_value);
    Funambol::ComplexData data(buffer);
    item.setData(&data);
    
    StatusCode rescode;
    if (e_Ok != (rescode = m_pProfileHolder->GetMOTreeManager()->Replace(fmState.c_str(), item, NULL)))
    {
        GDLDEBUG("REPLACE failed with %d", rescode);
        rescode = m_pProfileHolder->GetMOTreeManager()->Add(fmState.c_str(), item, NULL, false);
    }
    
    GDLDEBUG("Setting Status to %d finished with %d for FUMO node %s", m_value, rescode, m_uriFUMO.c_str());    
    return true;
}
