/*
 * 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 "NotificationListener/NotificationListener.h"
#include "NotificationListener/ConfigDefines.h"
#include "NotificationListener/ListenerThread.h"
#include "NotificationListener/MessageHandler.h"

#include "Starter.h"
#include "IRunner.h"

using namespace NS_DM_Client::NS_NotificationListener;
using namespace NS_DM_Client::NS_Common;
using namespace NS_DM_Client;

static int  DEFAULT_LISTEN_PORT = 2948;

NotificationListener::NotificationListener(void)
:
m_listener(0),
m_pch(0),
m_checkNMDiggest(true),
m_ListenerThread(0),
m_msgHandler(0),
m_msgHandlerThread(0),
m_logger(0)
{
}

NotificationListener::~NotificationListener(void)
{
    setListenerThread(NULL);
    setMessageHandlerThread(NULL);
    
	setListener(NULL);
	setHandler(NULL);
}

bool NotificationListener::Init(const StringMap& settings, const String& loggerInstance, ProfileComponentsHolder& pch)
{
    m_logger = &NS_Logging::GetLogger(loggerInstance.c_str());
    m_pch = &pch;

	StringMap& set = const_cast<StringMap&>(settings);

	const Funambol::StringBuffer& checkDiggest = set[c_CheckNotificationMsgDiggestParam];
	m_checkNMDiggest = (checkDiggest.empty()) ? true : atoi(checkDiggest.c_str()) != 0;

	const Funambol::StringBuffer& IP = set[c_ListenIPParam];
	m_IP = (IP.null()) ? UDPListener::ANY_ADDR : IP.c_str();

	const Funambol::StringBuffer& port = set[c_ListenPortParam];
	m_port = (port.empty()) ? DEFAULT_LISTEN_PORT : atoi(port.c_str());

	const Funambol::StringBuffer& DumpMsg = set[c_DumpMsgParam];
    bool dumpMessage = (DumpMsg.empty()) ? false : atoi(DumpMsg.c_str()) != 0;

	const Funambol::StringBuffer& DumpPath = set[c_DumpPathParam];
    if (DumpPath.empty())
    {
		m_dumpPath = "";
	}
	else
	{
		m_dumpPath = DumpPath;
	}

	const Funambol::StringBuffer& plainBootstrapParam = set[c_PlainBootstrap];
	bool plainBootstrap = (plainBootstrapParam.empty()) ? false : atoi(plainBootstrapParam.c_str()) != 0;

	const Funambol::StringBuffer& plainBootstrapCipherHdrParam = set[c_PlainBootstrapCipherHeaderPresent];
	bool plainBootstrapCipherHdr = (plainBootstrapCipherHdrParam.empty()) ? false : atoi(plainBootstrapCipherHdrParam.c_str()) != 0;

    LOG_DEBUG_(*m_logger, "%s = %d. ", c_CheckNotificationMsgDiggestParam, m_checkNMDiggest);
    LOG_DEBUG_(*m_logger, "%s = '%s'. ", c_ListenIPParam, m_IP.c_str());
    LOG_DEBUG_(*m_logger, "%s = %d. ", c_ListenPortParam, m_port);
    LOG_DEBUG_(*m_logger, "%s = %d. ", c_DumpMsgParam, dumpMessage);
    LOG_DEBUG_(*m_logger, "%s = %s. ", c_DumpPathParam, m_dumpPath.c_str());
	LOG_DEBUG_(*m_logger, "%s = %d. ", c_PlainBootstrap, plainBootstrap);
	LOG_DEBUG_(*m_logger, "%s = %d. ", c_PlainBootstrapCipherHeaderPresent, plainBootstrapCipherHdr);

	bool brc = false;

	setHandler(new MessageHandler(*m_pch, m_checkNMDiggest, plainBootstrap, (plainBootstrap) ? plainBootstrapCipherHdr : true, 
		*m_logger));

	if (!m_msgHandler)
	{
		LOG_ERROR_(*m_logger, "Failed to create MessageHandler");
	}

	setListener(new UDPListener(*m_logger));
	if (!m_listener)
	{
		LOG_ERROR_(*m_logger, "Failed to create UDP Listener");
	}
	else
	{
		m_listener->SetSettings(dumpMessage, (m_dumpPath.empty() ? NULL : m_dumpPath.c_str()));
		brc = m_listener->Init(m_IP.c_str(), m_port);
	}

	LOG_DEBUG_(*m_logger, "bRes = %d. ", brc);
    return brc;

}

bool NotificationListener::Start()
{
    if (!m_msgHandler)
    {
        return false;
    }
    setMessageHandlerThread(new Starter(*m_msgHandler));
    if (m_msgHandlerThread)
    {
        m_msgHandlerThread->start();
    }

    setListenerThread(new ListenerThread(*m_listener, m_msgHandler));
    if (m_ListenerThread)
    {
        m_ListenerThread->start();
    }

    LOG_DEBUG_(*m_logger, "ListenerThread = %p, MessageHandlerThread = %p ", m_ListenerThread, m_msgHandlerThread);
    return m_ListenerThread != NULL;
}

bool NotificationListener::Stop()
{
    m_msgHandlerThread->softTerminate();
    m_ListenerThread->softTerminate();
    bool brcL = m_ListenerThread->finished();
    bool brcM = m_msgHandlerThread->finished();
    LOG_DEBUG_(*m_logger, "ListenerThread finished = %d, MessageHandlerThread finished=%d. ", brcL, brcM);
    return brcL && brcM;
}

void NotificationListener::Release()
{
    LOG_DEBUG_(*m_logger, "THIS=%p. ", this);
}


void NotificationListener::setListenerThread(ListenerThread* lthread)
{
    if (m_ListenerThread)
    {
        delete m_ListenerThread;
    }

    m_ListenerThread = lthread;
}


void NotificationListener::setListener(UDPListener* listener)
{
	if (m_listener)
	{
		delete m_listener;
	}
	m_listener = listener;
}


void NotificationListener::setHandler(MessageHandler* handler)
{
    if (m_msgHandler)
    {
        delete m_msgHandler;
    }
    m_msgHandler = handler;
}


void NotificationListener::setMessageHandlerThread(Starter* thread)
{
    if (m_msgHandlerThread)
    {
        delete m_msgHandlerThread;
    }

    m_msgHandlerThread = thread;

}
