/*
 * Copyright (C) 2009 - 2010 Funambol, Inc.
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License version 3 as published by
 * the Free Software Foundation with the addition of the following permission
 * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED
 * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE
 * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program; if not, see http://www.gnu.org/licenses or write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301 USA.
 *
 * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite
 * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com.
 *
 * The interactive user interfaces in modified source and object code versions
 * of this program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU Affero General Public License version 3.
 *
 * In accordance with Section 7(b) of the GNU Affero General Public License
 * version 3, these Appropriate Legal Notices must retain the display of the
 * "Powered by Funambol" logo. If the display of the logo is not reasonably
 * feasible for technical reasons, the Appropriate Legal Notices must display
 * the words "Powered by Funambol".
 */

/* $Id$ */

#include "Logger/LoggerMacroses.h"
#include "serverexchange/MessageFactory.h"
#include "serverexchange/SendingStrategy.h"

using namespace NS_DM_Client;
using namespace NS_DM_Client::NS_Common;
using namespace NS_DM_Client::NS_Communication;

#define ACCEPT_BOTH_MIMES      "application/vnd.syncml.dm+xml, application/vnd.syncml.dm+wbxml"
#define PROPERTY_ACCEPT        "Accept"
#define PROPERTY_CONTENT_TYPE  "Content-Type"
#define PROPERTY_HMAC          "X-Syncml-Hmac"

static const char * c_LogName = "SendingStrategy";


SendingStrategy::SendingStrategy(ConnectionInfo &info, ISession &session) :
	m_connInfo(info),
	m_session(session)
{
}


SendingStrategy::Status SendingStrategy::Send(NS_SyncMLCommand::CommandStorage &cmds)
{
	MessageFactory factory(m_connInfo);
	int bytes_left = m_connInfo.settings.MaxMsgSize - factory.MessageSizeWithoutBody();
	
	for (int i=0; i<cmds.Size(); ++i)
	{
		if (bytes_left < 0)
			return NeedToSendLO;
		
		cmds[i]->Prepare();
		
		if (hasItemsSmallerThanMaxObjSize(cmds[i]))
		{
			int cmdsize = factory.AddCommand(cmds[i]);
			bytes_left -= cmdsize;
		}
		else
		{
			return NeedToSendLO;
		}
	}
	if (bytes_left < 0)
	{
		GDLDEBUG("bytes left: %d; switch to sending LO", bytes_left);
		return NeedToSendLO;
	}
	
	Funambol::StringBuffer *pSyncMLMessage = factory.GetMessage(!m_connInfo.IsInLOMode());
	GDLDEBUG("get message from factory, SB - %x", pSyncMLMessage);
	if (pSyncMLMessage)
	{
		m_session.SendMessage(*pSyncMLMessage);
		SAFE_DELETE(pSyncMLMessage);
	}
	else
	{
		GDLERROR("Failed to create message");
	}
	return SendingSucceded;
}


bool SendingStrategy::hasItemsSmallerThanMaxObjSize(NS_SyncMLCommand::SCommandPtr ptrCmd)
{
	if (!ptrCmd.get() || !ptrCmd->Internal().get() || !ptrCmd->Internal()->getItems())
	{
		return true;
	}

	Funambol::ArrayList *items = ptrCmd->Internal()->getItems();
	for (int i=0; i<items->size(); ++i)
	{
		Funambol::Item *item = (Funambol::Item *)items->get(i);
		if (item && item->getData())
		{
			const char *pData = item->getData()->getData();
			if (pData && (strlen(pData) > m_connInfo.settings.MaxObjSize))
			{
				GDLDEBUG("Check failed on item: %s [%d bytes]", ptrCmd->Internal()->getName(), strlen(pData));
				return false; // found item with data larger than MaxObjSize param
			}
		}
	}
	return true;
}
