/*
 * 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 "identifiers.h"
#include "lock.h"
#include "WBXMLUtils.h"

#include "daemon/INotificationCenter.h"
#include "executionqueue/ICommand.h"
#include "executionqueue/IExecutionQueue.h"
#include "serverexchange/IServerExchangeManager.h"

#include "serverexchange/ConnectionInfo.h"
#include "serverexchange/Connection.h"
#include "serverexchange/session/SessionsFactory.h"
#include "serverexchange/wrappers/SCommandFactory.h"
#include "serverexchange/wrappers/SStatusCommand.h"


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

static const char * c_LogName = "Connection";


Connection::Connection(ConnectionInfo &info) :
	m_connectionInfo(info),
	m_pProfileHolder(NULL),
	m_addInitialAlert(true),
	m_startNotified(false),
	m_threadStarted(false)
{
	terminate       = false;
	m_pSession      = NULL;
	m_pEventStarted = NULL;
	m_initialAlertCode = AC_CLIENT_INITIATED_MGMT;
}


Connection::~Connection()
{
	SAFE_DELETE(m_pSession);
}


void Connection::Abort()
{
	GDLDEBUG("received Abort");
	m_connectionInfo.msgState.SetCommandsCount(0);
	Lock lock(m_csConnection);

	m_connectionInfo.abortConnection = false;
	m_connectionInfo.SetLOMode(false);
	m_connectionInfo.SetWaitingForNextChunk(false);

	// clear connection
	SAFE_DELETE(m_pSession);

	m_waitingcommands.Lock();
	m_waitingcommands.Clear();
	m_waitingcommands.Unlock();
	GDLDEBUG("  aborted");
	notifySessionAborted();
}


void Connection::NotifySessionStarted()
{
	m_pProfileHolder->GetNotificationCenter()->SessionStarted(true);
}


void Connection::AddCommand(NS_SyncMLCommand::SCommandPtr ptrCommand, const char *serverid)
{
	Lock lock2(m_csHasCommands);

	if (!ptrCommand.get()) return;
	GDLDEBUG("Add command");

	SStatusCommand *pStatus = dynamic_cast<SStatusCommand*>(ptrCommand.get());
	if (pStatus)
	{
		if (!pStatus->GetMsgRef() || (pStatus->GetMsgRef() && (0 == strlen(pStatus->GetMsgRef()))))
		{
			pStatus->SetMsgRef(m_connectionInfo.LastServerMessageID());
		}

		if (pStatus->GetCmd() && strlen(pStatus->GetCmd()))
		{
			GDLDEBUG("received status of command '%s:%s'", pStatus->GetCmd(), pStatus->GetCmdRef());

			// status is response to command - dec
			if (m_connectionInfo.msgState.HasAllCommandsProcessed())
			{
				GDLERROR("CommandsToProcess is already zero !!!");
			}
			else
			{
				m_connectionInfo.msgState.DecCommandsCount();
				GDLDEBUG("count of commands still waiting for processing: %d", m_connectionInfo.msgState.GetCommandsCount());
			}
		}
	}

	m_waitingcommands.Lock();
	m_waitingcommands.Add(ptrCommand);
	m_waitingcommands.Unlock();

	m_condHasCommands.Signal();
}


void Connection::AddCommands(NS_SyncMLCommand::SCommandsArray &commands, const char *serverid)
{
	Lock lock2(m_csHasCommands);

	m_waitingcommands.Lock();
	if (commands.size())
		m_connectionInfo.msgState.IncCommandsCount(commands.size());

	for (size_t i=0; i<commands.size(); ++i)
	{
		SCommandPtr ptrCommand = commands[i];
		GDLERROR("status cmd %x", ptrCommand.get());
		if (!ptrCommand.get()) continue;

		SStatusCommand *pStatus = dynamic_cast<SStatusCommand*>(ptrCommand.get());
		GDLERROR("status cmd after dynamic_cast<> %x", pStatus);
		if (pStatus)
		{
			if (!pStatus->GetMsgRef() || (pStatus->GetMsgRef() && (0 == strlen(pStatus->GetMsgRef()))))
			{
				pStatus->SetMsgRef(m_connectionInfo.LastServerMessageID());
			}

			if (pStatus->GetCmd() && strlen(pStatus->GetCmd()))
			{
				GDLDEBUG("received status of command '%s:%s'", pStatus->GetCmd(), pStatus->GetCmdRef());

				// status is response to command - dec
				if (m_connectionInfo.msgState.HasAllCommandsProcessed())
				{
					GDLERROR("messageCommandsToProcess is already zero !!!");
				}
				else
				{
					m_connectionInfo.msgState.DecCommandsCount();
					GDLDEBUG("count of commands still waiting for processing: %d", m_connectionInfo.msgState.GetCommandsCount());
				}
			}
		}

		m_waitingcommands.Add(ptrCommand);
	}
	m_waitingcommands.Unlock();
	m_connectionInfo.msgState.DecCommandsCount(commands.size());
	GDLDEBUG("count of commands still waiting for processing: %d", m_connectionInfo.msgState.GetCommandsCount());
	m_condHasCommands.Signal();
}


void Connection::RequestSessionStart(const NS_NotificationListener::SessionInfo& sessionInfo)
{
	// TODO copy sessionInfo parameters to local members
	initiateConnection(AC_SERVER_INITIATED_MGMT,  &sessionInfo);
}


void Connection::SetPCH(ProfileComponentsHolder& pch)
{
	m_pProfileHolder = &pch;
}


void Connection::Start(Event *e)
{
	GDLDEBUG("[starting...");
	if (e)
		m_pEventStarted = e;
	terminate = false;

	FThread::start();
	GDLDEBUG("started]");
}


void Connection::Stop()
{
	GDLDEBUG("Received Stop ... [%s]", m_threadStarted ? "started" : "stopped");
	if (m_threadStarted)
	{
		terminate = true;
		m_condHasCommands.Signal();
		Abort();

		wait();
		terminate = false;
		m_threadStarted = false;
	}
	GDLDEBUG("terminated");
}


void Connection::StartSession(const AlertCode alertCode)
{
	initiateConnection(alertCode);
}


void Connection::StartSession(NS_SyncMLCommand::SAlertCommandPtr ptrAlert)
{
	m_addInitialAlert = false;
	AddCommand(ptrAlert, NULL);
}


void Connection::RequestFWUpdate(bool userInitiated, const char *fumouri, int data)
{
	// TODO - rework  to send Alert created somewhere else
	GDLDEBUG("RequestFWUpdate: %s initiated, FUMO uri >%s<, data %d", userInitiated ? "user" : "device", fumouri, data);

	m_addInitialAlert = false;
	AddCommand(SCommandFactory::CreateGenericAlert(fumouri,
												   userInitiated ? FW_UPDATE_USER_REQUEST : FW_UPDATE_DEVICE_REQUEST,
												   data
												   ));
}


void Connection::Wait()
{
	// wait for the ServerExchangeManager to stop.
	// Mutex m_mutexWaitComplete is locked on the very start of the SEM run loop
	if (m_threadStarted)
	{
		Lock lock(m_csWaitComplete);
	}
}


void Connection::finishSession()
{
	if (m_pSession)
	{
		notifySessionFinished();
	}

	SAFE_DELETE(m_pSession);
}


void Connection::createSession()
{
	SAFE_DELETE(m_pSession);
	GDLDEBUG("Create session %s, %s",
			 m_connectionInfo.acconfig.getClientAuthType(),
			 m_addInitialAlert ? "add default init alert" : "custom init alert added");

	m_pSession = SessionsFactory::CreateSession(m_connectionInfo);
	if (m_pSession)
	{
		m_pSession->SetAddInitialAlert(m_addInitialAlert);
		m_pSession->SetStartAlertCode(m_initialAlertCode);
		m_pSession->SetCommandsSink(*this);
		m_pSession->SetPCH(*m_pProfileHolder);
	}
	else
		GDLERROR("failed to create session of type %s", m_connectionInfo.acconfig.getClientAuthType());

	m_addInitialAlert = true;
	m_initialAlertCode = AC_CLIENT_INITIATED_MGMT;
}


void Connection::notifySessionAborted()
{
	m_pProfileHolder->GetNotificationCenter()->SessionAborted();
	m_startNotified = false;
}


void Connection::notifySessionStarted()
{
	if (!m_startNotified && m_connectionInfo.IsAuthenticated())
	{
		m_pProfileHolder->GetNotificationCenter()->SessionStarted(true);
		m_startNotified = true;
	}
}


void Connection::notifySessionFinished()
{
	m_pProfileHolder->GetNotificationCenter()->SessionFinished();
	m_startNotified = false;
}


void Connection::run()
{
	m_threadStarted = true;
	Lock lock(m_csWaitComplete);

	int count = 0;
	while (!terminate)
	{
		if (m_pEventStarted)
		{
			GDLDEBUG("[before signal ...");
			m_pEventStarted->signal();
			GDLDEBUG("after signal]");
			m_pEventStarted = NULL;
		}

		if (m_connectionInfo.connectionFinished)
		{
			Lock lock2(m_csHasCommands);

			if (m_connectionInfo.reconnectInstantly)
			{
				GDLDEBUG("stop connection, reconnect instantly");
				SAFE_DELETE(m_pSession);
				m_connectionInfo.reconnectInstantly = false;
			}
			else if (!m_waitingcommands.Size())
			{
				GDLDEBUG("0 waiting commands");
				finishSession();
				m_condHasCommands.Wait(m_csHasCommands);

				if (terminate)
					break;
			}
		}


		// TODO - refactor to lock CS in session, CS should be connected with CV
		if (m_csConnection.TryLock())
			continue;

		if (isAccessConfigValid())
		{
			GDLDEBUG("");
			GDLDEBUG("Connection # %d", ++count);

			m_connectionInfo.msgState.SetCommandsCount(0);
			if (!m_pSession)
				createSession();

			m_pSession->Connect(m_waitingcommands);
			if (m_connectionInfo.abortConnection)
				Abort();
			else
				notifySessionStarted();

			// TODO - refactor to wait on CV passed to Session object
			m_connectionInfo.msgState.Wait();
			GDLDEBUG("all commands processed");
		}
		else
		{
			GDLDEBUG("[%d] ATTENTION Config info is not consistent", count);
		}

		m_csConnection.Unlock();
	}
	GDLDEBUG("Connection finished");
}


void Connection::initiateConnection(const NS_SyncMLCommand::AlertCode alertCode, const NS_NotificationListener::SessionInfo* sessionInfo)
{
	GDLDEBUG("initiate connecttion with alert '%d'", alertCode);
	GDLDEBUG("SessionInfo = %x", sessionInfo);
	if (!m_connectionInfo.devinf.get())
	{
		GDLERROR("  stored DevInf is NULL; session will not be initiated");
		return;
	}
	
	// TODO
	if (m_pSession && m_pSession->IsSendingLO())
	{
		GDLDEBUG("  sending LO; session will not be initiated");
		return;
	}

	if (0 == m_csConnection.TryLock())
	{
		// TODO
		if (m_pSession && m_pSession->IsSendingLO())
		{
			m_csConnection.Unlock();
			GDLDEBUG("skipping - Sending LO (2)");
			return;
		}
		// clear m_sendingQueue ?!
		// block thread from entering SendState

		if (sessionInfo)
		{
			GDLERROR("Session id from the request: '%s'", sessionInfo->serverID.c_str());
			if (!sessionInfo->sessionID.empty())
			{
				m_connectionInfo.SetSessionID(sessionInfo->sessionID.c_str());
			}
		}

		// add Replace command with DevInfo in it
		Lock lock2(m_csHasCommands);
		m_initialAlertCode = alertCode;

		m_connectionInfo.SetSessionURL(m_connectionInfo.acconfig.getSyncURL());
		m_csConnection.Unlock();

		m_condHasCommands.Signal();
	}
	else
	{
		GDLDEBUG("Cannot lock Connection");
	}
}


// TODO - move this check to the ConnectionInfo class
bool Connection::isAccessConfigValid()
{
	Funambol::AccessConfig &ac = m_connectionInfo.acconfig;
	const char * url = ac.getSyncURL();
	if (!url || !url[0]) {
		GDLERROR("sync url is empty");
		return false;
	}

	const char * uname = ac.getUsername();
	if (!uname || !uname[0])
	{
		GDLERROR("username is empty");
		return false;
	}

	return true;
}

