/*
 * Copyright 2009 Funambol, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/* $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(std::nothrow) MessageHandler(*m_pch, m_checkNMDiggest, plainBootstrap, (plainBootstrap) ? plainBootstrapCipherHdr : true, 
        *m_logger));

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

    setListener(new(std::nothrow) 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(std::nothrow) Starter(*m_msgHandler));
    if (m_msgHandlerThread)
    {
        m_msgHandlerThread->start();
    }

    setListenerThread(new(std::nothrow) 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;

}
