/*
* 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 "IMOTreeCommand.h"
#include "treemanager/IMOTreeManager.h"
#include "executionqueue/ICommandDispatcher.h"
#include "ManagementObjects/IMgmtObject.h"
#include "Logger/Logger.h"
#include "Event.h"

namespace NS_DM_Client
{
	IMOTreeCommand::IMOTreeCommand(ProfileComponentsHolder* holder,  
		IMgmtObject* mgmtObject, NS_Common::EventEx* executionCompleted, bool& executionResult): 
			m_componentHolder(holder), m_mgmtObject(mgmtObject), m_executionCompleted(executionCompleted), 
			m_executionResult(executionResult), m_logger(NS_Logging::GetLogger("ClientAdapterStub")), m_started(false)
	{}
	//------------------------------------------------------------------------------------------------------

	IMOTreeCommand::~IMOTreeCommand()
	{
		if (!m_started)
		{
			m_executionResult = false; // command was not executed at all
			if (m_executionCompleted) m_executionCompleted->signal();
		}
	}
	//------------------------------------------------------------------------------------------------------

	bool IMOTreeCommand::Execute()
	{
		m_started = true;

		LOG_(m_logger, "IMOTreeCommand::Execute start");
		IMOTreeManager* treeManager = m_componentHolder->GetMOTreeManager();
		if (!treeManager)
		{
			m_executionResult = false;
			if (m_executionCompleted) m_executionCompleted->signal();

			LOG_ERROR_(m_logger, "Failed to get MOTreeManager from profile");
			return false;
		}
		bool result = m_executionResult = run(*treeManager);
		if (!m_executionResult)
		{
			LOG_ERROR_(m_logger, "Command execution failed");
		}
		LOG_(m_logger, "IMOTreeCommand::Execute end, result = %d", m_executionResult);
		if (m_executionCompleted) m_executionCompleted->signal();
		return result;
	}
	//-------------------------------------------------------------------------------------------

	bool IMOTreeCommand::invokeResult()
	{
		return true;
	}

}
