/*
 * 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 i<s 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 "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_serverInitiated(false),
    m_startNotified(false),
    m_threadStarted(false)
{
GDLINFO("Enter");
    terminate       = false;
    m_pSession      = NULL;
    m_pEventStarted = NULL;
    m_initialAlertCode = AC_CLIENT_INITIATED_MGMT;
GDLINFO("Leave");
}


Connection::~Connection()
{
GDLINFO("Enter");
    SAFE_DELETE(m_pSession);
GDLINFO("Leave");
}


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

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

    // clear connection
    SAFE_DELETE(m_pSession);
    m_connectionInfo.Reset();

    m_waitingcommands.Lock();
    m_waitingcommands.Clear();
    m_waitingcommands.Unlock();
    GDLDEBUG("  aborted");
    notifySessionAbort();
GDLINFO("Leave");
}


void Connection::AddCommand(NS_SyncMLCommand::SCommandPtr ptrCommand, const char *serverid)
{
GDLINFO("Enter");

    if (ptrCommand.get() == NULL)
    {
        GDLWARN("ptrCommand is NULL");
        GDLINFO("Leave");
        return;
    }

    NS_SyncMLCommand::SCommandsArray cmds;
    cmds.push_back(ptrCommand);
    AddCommands(cmds, serverid);
GDLINFO("Leave");
}


void Connection::AddCommands(NS_SyncMLCommand::SCommandsArray &commands, const char *serverid)
{
GDLINFO("Enter");
    GDLDEBUG("Add commands [%d]", commands.size());
    if (commands.empty())
    {
        GDLWARN("commands is empty");
        return;
    }

    Lock lock(m_csHasCommands);

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

    for (size_t i=0; i<commands.size(); ++i)
    {
        SCommandPtr ptrCommand = commands[i];
        GDLDEBUG("command %x", ptrCommand.get());
        if (ptrCommand.get() == NULL)
        {
            GDLWARN("ptrCommand is NULL");
            continue;
        }

        ptrCommand->Prepare();
        if (ptrCommand->Internal().get() && !strcmp(ptrCommand->Internal()->getName(), STATUS_COMMAND_NAME))
        {
            SStatusCommand *pStatus = static_cast<SStatusCommand*>(ptrCommand.get());
            if (!pStatus->GetMsgRef() || (0 == strlen(pStatus->GetMsgRef())))
            {
                pStatus->SetMsgRef(m_connectionInfo.LastServerMessageID());
                pStatus->Internal()->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_evHasCommands.signal();
GDLINFO("Leave");
}


void Connection::RequestSessionStart(const NS_NotificationListener::SessionInfo& sessionInfo)
{
GDLINFO("Enter");
    // TODO copy sessionInfo parameters to local members
    m_serverInitiated = true;
    
    GDLDEBUG("sessionInfo.serverInitiated=%d", sessionInfo.serverInitiated);
    initiateConnection(sessionInfo.serverInitiated ? AC_SERVER_INITIATED_MGMT : AC_CLIENT_INITIATED_MGMT,
                       &sessionInfo);
GDLINFO("Leave");
}


void Connection::SetPCH(ProfileComponentsHolder& pch)
{
GDLINFO("Enter");

    m_pProfileHolder = &pch;
GDLINFO("Leave");
}


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

//  FThread::start();
    Thread::start();
    GDLDEBUG("started]");
GDLINFO("Leave");
}


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

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


void Connection::StartSession(const AlertCode alertCode)
{
GDLINFO("Enter");
    GDLDEBUG("start session with alert code %d", alertCode);
    m_serverInitiated = false;
    m_initialAlert.reset();
    initiateConnection(alertCode);
GDLINFO("Leave");
}


void Connection::StartSession(NS_SyncMLCommand::SAlertCommandPtr ptrAlert)
{
GDLINFO("Enter");

    if (ptrAlert.get() == NULL)
    {
        GDLWARN("ptrAlert is NULL");
        return;
    }

//  m_addInitialAlert = false;
    m_serverInitiated = false;
    GDLDEBUG("start session with custom Alert, %x", ptrAlert.get());
    m_initialAlert = ptrAlert;
//  AddCommand(ptrAlert, NULL);
    initiateConnection(ptrAlert);
GDLINFO("Leave");
}


void Connection::RequestFWUpdate(bool userInitiated, const char *fumouri, int data)
{
GDLINFO("Enter");
    // 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
                                                   ));
GDLINFO("Leave");
}


void Connection::Wait()
{
GDLINFO("Enter");

    // 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);
    }
GDLINFO("Leave");
}


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

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

    m_initialAlertCode = AC_CLIENT_INITIATED_MGMT;
GDLINFO("Leave");
}


void Connection::finishSession()
{
GDLINFO("Enter");

    if (m_pSession)
    {
        notifySessionFinished();
    }
    
    SAFE_DELETE(m_pSession);
    m_connectionInfo.Reset();
    m_connectionInfo.SetLOMode(false);
    m_addInitialAlert = true;
GDLINFO("Leave");
}


void Connection::notifyAuthenticationFailure()
{
GDLINFO("Enter");

    m_pProfileHolder->GetNotificationCenter()->NotifyDMSessionStatus(e_sessionEnd, e_unknownInitiator, e_authentication);
    m_startNotified = false;
GDLINFO("Leave");
}


void Connection::notifySessionAbort()
{
GDLINFO("Enter");

    m_pProfileHolder->GetNotificationCenter()->NotifyDMSessionStatus(e_sessionEnd, e_network, e_abort);
    m_startNotified = false;
GDLINFO("Leave");
}


void Connection::notifySessionStart()
{
GDLINFO("Enter");

    if (!m_startNotified && m_connectionInfo.IsAuthenticated())
    {
        m_pProfileHolder->GetNotificationCenter()->NotifyDMSessionStatus(e_sessionStart, 
                                                                         m_serverInitiated ? e_network : e_user, 
                                                                         e_successful);
        m_startNotified = true;
GDLINFO("Leave");
    }
}


void Connection::notifySessionFinished()
{
GDLINFO("Enter");

    m_pProfileHolder->GetNotificationCenter()->NotifyDMSessionStatus(e_sessionEnd, e_network, e_successful);
    m_startNotified = false;
GDLINFO("Leave");
}


void Connection::run()
{
GDLINFO("Enter");

    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.state.connectionFinished)
        {
            GDLDEBUG("connection finished");
            bool commandsAvailable = false;
            {
                Lock lock2(m_csHasCommands);
                commandsAvailable = m_waitingcommands.Size() > 0;
                GDLDEBUG(commandsAvailable ? "commands available" : "no commands available");
                if (!commandsAvailable) m_evHasCommands.reset();
            }

            if (m_connectionInfo.state.reconnectInstantly)
            {
                GDLDEBUG("stop connection, reconnect instantly");
                SAFE_DELETE(m_pSession);
//              m_connectionInfo.Reset();
                m_connectionInfo.state.reconnectInstantly = false;
            }
            else if (!commandsAvailable)
            {
                GDLDEBUG("0 waiting commands");
                finishSession();
                
                if (m_alerts.size())
                {
                    NS_SyncMLCommand::SAlertCommandPtr ptrAlert;
                    if(ptrAlert.get() == NULL)
                    {
                        GDLWARN("ptrAlert is NULL");
                    }

                    {
                        Lock lock(m_csHasCommands);
                        ptrAlert = m_alerts.back();
                        m_alerts.pop_back();
                    }
                    
                    initiateConnection(ptrAlert);
                }
                
                GDLDEBUG("wait for new commands");
                GDLDEBUG("");
                m_evHasCommands.wait();
                GDLDEBUG("new commands available");
                if (terminate) 
                    break;
            }
        }


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

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

            m_connectionInfo.msgState.SetCommandsCount(0);
            GDLDEBUG("connect to URL: '%s'", m_connectionInfo.GetSessionURL());

            if (!m_pSession)
                createSession();
            notifySessionStart();
            m_pSession->Connect(m_waitingcommands);
            if (m_connectionInfo.state.authenticationFailed)
                notifyAuthenticationFailure();
            
            if (m_connectionInfo.state.abortConnection)
                Abort();
//          else
//              notifySessionStarted(); // TODO - send session's type in notification

            // 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");
GDLINFO("Leave");
}


void Connection::initiateConnection(const NS_SyncMLCommand::AlertCode alertCode, const NS_NotificationListener::SessionInfo* sessionInfo)
{
GDLINFO("Enter");
    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())
    {
        GDLDEBUG("connection locked");
        // 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("Server id from the request: '%s'",  sessionInfo->serverID.c_str());
            GDLERROR("Session id from the request: '%s'", sessionInfo->sessionID.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();
        GDLDEBUG("connection unlocked");

        m_evHasCommands.signal();
    }
    else
    {
        GDLDEBUG("Cannot lock Connection");
    }
GDLINFO("Leave");
}

void Connection::initiateConnection(NS_SyncMLCommand::SAlertCommandPtr ptrAlert)
{
GDLINFO("Enter");
    if(ptrAlert.get() == NULL)
    {
        GDLWARN("ptrAlert is NULL");
    }

    GDLDEBUG("initiate connection with alert command");
    if (!m_connectionInfo.devinf.get())
    {
        GDLERROR("  stored DevInf is NULL; session will not be initiated");
        return;
    }

    if (0 == m_csConnection.TryLock())
    {
        GDLDEBUG("connection locked");
        if (m_pSession)
        {
            if (m_pSession->IsSendingLO())
            {
                m_csConnection.Unlock();
                GDLDEBUG("skip session init - Sending LO (2)");
                return;
            }
            else
            {
                m_waitingcommands.Lock();
                m_waitingcommands.Add(ptrAlert);
                m_waitingcommands.Unlock();
                m_csConnection.Unlock();
                return;
            }
        }

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

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

        m_addInitialAlert = false;
        m_initialAlert = ptrAlert;

        m_csConnection.Unlock();

        m_evHasCommands.signal();
    }
    else
    {
        GDLDEBUG("failed to lock Connection, postpone alert");
        // postpone session
        Lock lock(m_csHasCommands);
        m_alerts.insert(m_alerts.begin(), ptrAlert);
    }
GDLINFO("Leave");
}


bool Connection::isAccessConfigValid()
{
GDLINFO("Enter");

    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;
    }
GDLINFO("Leave");

    return true;
}


bool Connection::shouldStartSession()
{
    return m_initialAlert.get() != NULL;
}
