/*
 * 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 "NotificationListener/DMSessionRequestCommand.h"
#include "daemon/ProfileComponentsHolder.h"
#include "serverexchange/IServerExchangeManager.h"
#include "treemanager/IMOTreeManager.h"
#include "treemanager/TreeManagerUtils.h"

#include "Logger/LoggerMacroses.h"

using namespace NS_DM_Client::NS_NotificationListener;
using namespace NS_DM_Client;

static const char * c_LogName = "ServerExchangeManager";

DMSessionRequestCommand::DMSessionRequestCommand(ProfileComponentsHolder& pch, NS_Logging::Logger& logger)
	: ServerExchangeCommand(*pch.GetServerExchangeManager()), m_pch(pch), m_checkDiggest(false), m_hasSessionInfo(false), m_logger(logger)
{
}


DMSessionRequestCommand::DMSessionRequestCommand(const SessionInfo& sessionInfo, bool checkDiggest,
												 ProfileComponentsHolder& pch, NS_Logging::Logger& logger)
	: ServerExchangeCommand(*pch.GetServerExchangeManager()), m_pch(pch),
	m_sessionInfo(sessionInfo), m_checkDiggest(checkDiggest), m_hasSessionInfo(true), m_logger(logger)
{
}


DMSessionRequestCommand::~DMSessionRequestCommand()
{
}


bool DMSessionRequestCommand::Execute()
{
	bool result = false;

	if (m_hasSessionInfo)
		// get DMAcc with the serverID
		if (TMUtils::HasAccount(*m_pch.GetMOTreeManager(), m_sessionInfo.serverID))
		{
			// check diggest (if required)
			if (!m_checkDiggest || validDiggest())
			{
				// notify ServerExchangeManager
				m_pch.GetServerExchangeManager()->RequestSessionStart(m_sessionInfo);

				result = true;
			}
		}
	else
	{
		String serverID;
		TMUtils::GetFirstAccount(*m_pch.GetMOTreeManager(), serverID);
		if (!serverID.empty())
		{
			m_sessionInfo.serverID = serverID;
			m_sessionInfo.serverInitiated = false;
			m_pch.GetServerExchangeManager()->RequestSessionStart(m_sessionInfo);
		}
		else
			LDEBUG("no accounts found in the mo tree");
	}

    return result;
}


bool DMSessionRequestCommand::validDiggest()
{
	bool valid = true;
	LDEBUG("hardcoded result=%d", valid);
	return true;
}
