/*
 * 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 <base/util/utils.h>
#include <Utils.h>
#include <serverexchange/ConnectionInfo.h>
#include <Logger/LoggerMacroses.h>

using namespace NS_DM_Client::NS_Communication;

static const char * c_LogName = "ConnectionInfo";

ConnectionInfo::ConnectionInfo() :
	abortConnection(false), 
	hasLOSending(false), hasToResendLastCommands(false), hasToSendNextChunk(false), 
	connectionFinished(true),
	reconnectInstantly(false),
	repeatAuthentication(false),
	m_messageID(0),
	m_isAuthenticated(false),
	m_isDevInfSent(false),
	m_isInLOMode(false),
	m_isWaitingAuthentication(false), 
	m_isWaitingForNextChunk(false),
	m_useHMAC(false),
	m_askNextChunkAlertCmdID(NULL), m_sessionURL(NULL), m_serverID(NULL), 
	m_nextNonce(NULL), m_nonce(NULL),
	m_messageIDText(NULL), m_lastServerMessageID(NULL),
	m_sessionID(NULL)
{
    m_messageIDText = Funambol::stringdup("1");
    m_lastServerMessageID = Funambol::stringdup("");
	acconfig.setUsername("");
	acconfig.setPassword("");
	acconfig.setProxyHost("");
	acconfig.setProxyUsername("");
	acconfig.setProxyPassword("");
	acconfig.setClientAuthType("");
	acconfig.setServerAuthType("");
	acconfig.setServerPWD("");
	acconfig.setServerID("");
	acconfig.setServerNonce("");
	acconfig.setClientNonce("");
	acconfig.setUserAgent("");
}


ConnectionInfo::~ConnectionInfo()
{
	SAFE_DELETE_ARR(m_askNextChunkAlertCmdID);
	SAFE_DELETE_ARR(m_sessionURL);
	SAFE_DELETE_ARR(m_nextNonce);
	SAFE_DELETE_ARR(m_nonce);
	SAFE_DELETE_ARR(m_messageIDText);
	SAFE_DELETE_ARR(m_lastServerMessageID);
	SAFE_DELETE_ARR(m_sessionID);
	SAFE_DELETE_ARR(m_serverID);
}


void ConnectionInfo::SetAuthenticated(bool b)
{
	m_isAuthenticated = b;
	if (b)
		m_isWaitingAuthentication = false;
	else
	{
		ResetMessageID();
		m_isDevInfSent = false;
	}
}


void ConnectionInfo::ResetMessageID()
{
	m_messageID = 0;
}


char * ConnectionInfo::GetNextMessageID()
{
	SAFE_DELETE_ARR(m_messageIDText);

	m_messageID++;

	char bf[64];
	__sprintf(bf, "%d", m_messageID);
	m_messageIDText = Funambol::stringdup(bf);

	return m_messageIDText;
}


void ConnectionInfo::SetWaitingAuthentication(bool b)
{
	m_isWaitingAuthentication = b;
	if (b)
		m_isAuthenticated = false;
}


void ConnectionInfo::SetLastServerMessageID(const char *theID)
{
	SAFE_DELETE_ARR(m_lastServerMessageID);
	if (theID)
		m_lastServerMessageID = Funambol::stringdup(theID);
	else
		m_lastServerMessageID = Funambol::stringdup("");
}


void ConnectionInfo::SetNextChunkAlertCmdID(const char *theID)
{
	SAFE_DELETE_ARR(m_askNextChunkAlertCmdID);
	if (theID)
		m_askNextChunkAlertCmdID = Funambol::stringdup(theID);
	else
		m_askNextChunkAlertCmdID = Funambol::stringdup("");
}


const char * ConnectionInfo::GetNextNonce()
{
	SAFE_DELETE_ARR(m_nonce);
	m_nonce = Funambol::stringdup(m_nextNonce);

	Funambol::NextNonce *pNonce = CreateNonce();
	const char *nonce64 = pNonce->getValueAsBase64(); // result created with new []
	m_nextNonce = const_cast<char*>(nonce64);

	return m_nonce;
}


void ConnectionInfo::SetSessionURL(const char *url)
{
	SAFE_DELETE_ARR(m_sessionURL);
	m_sessionURL = Funambol::stringdup(url);
}


const char * ConnectionInfo::GetSessionURL()
{
	return m_sessionURL;
}


void ConnectionInfo::SetServerID(const char *sid)
{
	SAFE_DELETE_ARR(m_serverID);
	m_serverID = Funambol::stringdup(sid);
}


void ConnectionInfo::SetSessionID(const char *sid)
{
	SAFE_DELETE_ARR(m_sessionID);
	m_sessionID = Funambol::stringdup(sid);
}



void ConnectionInfo::SwitchToSessionType(const char *name)
{
	if (name && strlen(name))
	{
		if (!initialClientSessionType.size())
			initialClientSessionType = acconfig.getClientAuthType();
		acconfig.setClientAuthType(name);
		reconnectInstantly = true;
	}
}


bool ConnectionInfo::IsServerCredValid(Funambol::Cred *cred)
{
	if (cred && cred->getData() && cred->getFormat() && cred->getType())
	{
		const char *data   = cred->getData();
		const char *format = cred->getFormat();
		const char *type   = cred->getType();
		
		if (!strcmp(AUTH_TYPE_BASIC, type) && !strcmp("b64", format))
		{
			Funambol::Authentication auth(AUTH_TYPE_BASIC, acconfig.getServerID(), acconfig.getServerPWD());
			return !strcmp(cred->getData(), auth.getData());
		}
		else if (!strcmp(AUTH_TYPE_MD5, type) && !strcmp("b64", format))
		{
			char *localmd5 = Funambol::MD5CredentialData(acconfig.getServerID(), acconfig.getServerPWD(), acconfig.getServerNonce());
			GDLDEBUG("Local md5 calc: %s", localmd5);
//			GDLDEBUG("on auth data: ['%s' '%s' '%s']", acconfig.getServerID(), acconfig.getServerPWD(), acconfig.getServerNonce());
			
			bool res = localmd5 && data && !strcmp(localmd5, data);
			SAFE_DELETE_ARR(localmd5);
			return res;
		}
		else
			GDLERROR("Unsupported cred type received: %s", type);
	}
	return false;
}

void ConnectionInfo::Reset()
{
	if (initialClientSessionType.size())
	{
		acconfig.setClientAuthType(initialClientSessionType.c_str());
		initialClientSessionType = "";
	}
	abortConnection = false;
	hasLOSending = false;
	hasToResendLastCommands = false;
	hasToSendNextChunk = false;
	connectionFinished = true;
	reconnectInstantly = false;
	repeatAuthentication = false;
	m_messageID = 0;
	SetSessionID(NULL);

// 	SAFE_DELETE_ARR(m_nonce);
// 	SAFE_DELETE_ARR(m_nextNonce);
// 	m_nextNonce = Funambol::stringdup(acconfig.getServerNonce());
}

