/*
 * Copyright 2010 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 "lock.h"
#include "serverexchange/ConnectionInfo.h"
#include "serverexchange/session/SessionsFactory.h"
#include "serverexchange/session/BasicSession.h"
#include "serverexchange/session/HMACSession.h"
#include "serverexchange/session/MD5Session.h"
#include <Logger/LoggerMacroses.h>

const char* const c_LogName = "SessionsFactory";

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


SessionsFactory::SessionsFactory() : m_pTransportCreator(NULL)
{
}


SessionsFactory::~SessionsFactory()
{
    SAFE_DELETE(m_pTransportCreator);
}


ISession * SessionsFactory::CreateSession(ConnectionInfo &info)
{
    ISession *pSession = NULL;
    Funambol::TransportAgent *pTA = NULL;
    if (m_pTransportCreator)
    {
        pTA = m_pTransportCreator->CreateTransportAgent();
    }
    else
    {
        Funambol::URL url("");
        Funambol::Proxy proxy;
        pTA = Funambol::TransportAgentFactory::getTransportAgent(url, proxy);
    }
    
    if (pTA != NULL)
    {
        const char *authType = info.acconfig.getClientAuthType();

        if (!strcmp(AUTH_TYPE_BASIC, authType))
            pSession = new(std::nothrow) BasicSession(info, *pTA);
        else if (!strcmp(AUTH_TYPE_MD5, authType))
            pSession = new(std::nothrow) MD5Session(info, *pTA);
        else if (!strcmp(AUTH_TYPE_MAC, authType))
            pSession = new(std::nothrow) HMACSession(info, *pTA);

        if(pSession == NULL)
        {
            GDLWARN("new Session");
        }
    }

    return pSession;
}


SessionsFactory & SessionsFactory::Instance()
{
    Lock lock(m_csCreate);
    
    if (!m_pFactoryInstance)
    {
        m_pFactoryInstance = new(std::nothrow) SessionsFactory();
        if(m_pFactoryInstance == NULL) GDLWARN("new SessionsFactory");
    }
    
    return *m_pFactoryInstance;
}


void SessionsFactory::SetTransportCreator(TransportCreator &trcreator)
{
    SAFE_DELETE(m_pTransportCreator);
    m_pTransportCreator = &trcreator;
}


CritSection       SessionsFactory::m_csCreate;
SessionsFactory * SessionsFactory::m_pFactoryInstance;

