/*
 * 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 <syncml/core/ComplexData.h>
#include <syncml/core/Item.h>
#include <syncml/core/Meta.h>
#include "executionqueue/IExecutionQueue.h"
#include "serverexchange/commands/DRMDReadyNotificationCommand.h"
#include "serverexchange/commands/MockTriggerDRMDCommand.h"
#include "common/PropertiesReader.h"
#include "treemanager/IMOTreeManager.h"

using namespace NS_Common;
using namespace NS_DM_Client;

MockTriggerDRMDCommand::MockTriggerDRMDCommand(ProfileComponentsHolder *pch, String &filepath) :
	TriggerDRMDCollectingCommand(pch), m_filepath(filepath)
{
}

MockTriggerDRMDCommand::MockTriggerDRMDCommand(ProfileComponentsHolder *pch, const char *filepath) :
	TriggerDRMDCollectingCommand(pch), m_filepath(filepath)
{
	
}

bool MockTriggerDRMDCommand::requestData(int duration)
{
	if (!m_pch->GetMOTreeManager()) return false;

	IMOTreeManager &tm = *m_pch->GetMOTreeManager(); 
	Funambol::ComplexData data;
	Funambol::Item item;
	Funambol::Meta meta;
	meta.setFormat("chr");
	meta.setType("text/plain");
	item.setMeta(&meta);
	
	// read data 
	PropertiesReader preader(m_filepath);
	PropertiesReader::Properties::iterator it = preader.begin();
	while (it != preader.end())
	{
		data.setData(it->value.c_str());
		item.setData(&data);
		if (e_Ok != tm.Add(it->name, item))
			tm.Replace(it->name, item);
		it++;
	}
	
	// notify data ready
	ICommand *cmd = new DRMDReadyNotificationCommand(m_pch);
	if (!m_pch->GetExecutionQueue() || ! m_pch->GetExecutionQueue()->Add(*cmd))
	{	
		delete cmd;
		return false;
	}
	
	return true;
}
