/* 
ZLib license:
Copyright (c) 2011 Dirk de la Hunt

This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software.

Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:

1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef __DEBUG

#include "chatengine.h"
#include "utils.h"

using namespace gloox;

ChatEngine::ChatEngine()
{
	session         = 0;
	connectAttempts = 0;
	waitTime        = 65;
	quitting        = false;
	options         = 0;
	client          = 0;
}

ChatEngine::~ChatEngine() 
{
	delete client;
}

void ChatEngine::Start(MonkeyOptions *Options)
{
	delete client;

	options = Options;

	JID jid(Options->Username.Buffer());
	client = new Client(jid, Options->Password.Buffer());
	client->setServer(Options->Server.Buffer());
	client->registerConnectionListener(this);
	client->registerMessageSessionHandler(this, 0);
	client->disco()->setVersion("MonkeyBot", "0.1", "Linux");
	client->disco()->setIdentity("client", "bot");
	client->disco()->addFeature(XMLNS_CHAT_STATES);

	if (client->connect(false))
	{
		ConnectionError ce = ConnNoError;
		while (ce == ConnNoError)
		{
			ce = client->recv();
		}
	}

	delete client;
	client = 0;
}

void ChatEngine::onConnect()
{
	printf("Connected.\n");
	connectAttempts = 0;
	waitTime        = 65;
}

void ChatEngine::onDisconnect(ConnectionError Error)
{
	printf("Disconnected: %d\n", Error);
	if (Error == ConnAuthenticationFailed)
	{
		printf("Authentication failed, reason: %d\n", client->authError());
	}
	else if (!quitting)
	{
		connectAttempts++;
		printf("Reconnecting in %d seconds...\n", waitTime);
		Utils::Sleep(waitTime);
		Start(options);
		if (connectAttempts > 2)
			waitTime = 60 * 5;
		if (connectAttempts > 5)
			waitTime = 60 * 15;
		if (connectAttempts > 10)
			waitTime = 60 * 30;
	}
}

bool ChatEngine::onTLSConnect(const CertInfo &Info)
{
	return true;
}

void ChatEngine::handleMessageSession(MessageSession *Session)
{
	printf("New session.\n");
	client->disposeMessageSession(session);
	session = Session;
	session->registerMessageHandler(this);
}

#endif

