/* ***** BEGIN LICENSE BLOCK *****
 * Source last modified: $Id: hxsymbianapman.cpp,v 1.2.2.2 2004/07/09 02:08:48 hubbe Exp $
 * 
 * Portions Copyright (c) 1995-2004 RealNetworks, Inc. All Rights Reserved.
 * 
 * The contents of this file, and the files included with this file,
 * are subject to the current version of the RealNetworks Public
 * Source License (the "RPSL") available at
 * http://www.helixcommunity.org/content/rpsl unless you have licensed
 * the file under the current version of the RealNetworks Community
 * Source License (the "RCSL") available at
 * http://www.helixcommunity.org/content/rcsl, in which case the RCSL
 * will apply. You may also obtain the license terms directly from
 * RealNetworks.  You may not use this file except in compliance with
 * the RPSL or, if you have a valid RCSL with RealNetworks applicable
 * to this file, the RCSL.  Please see the applicable RPSL or RCSL for
 * the rights, obligations and limitations governing use of the
 * contents of the file.
 * 
 * Alternatively, the contents of this file may be used under the
 * terms of the GNU General Public License Version 2 or later (the
 * "GPL") in which case the provisions of the GPL are applicable
 * instead of those above. If you wish to allow use of your version of
 * this file only under the terms of the GPL, and not to allow others
 * to use your version of this file under the terms of either the RPSL
 * or RCSL, indicate your decision by deleting the provisions above
 * and replace them with the notice and other provisions required by
 * the GPL. If you do not delete the provisions above, a recipient may
 * use your version of this file under the terms of any one of the
 * RPSL, the RCSL or the GPL.
 * 
 * This file is part of the Helix DNA Technology. RealNetworks is the
 * developer of the Original Code and owns the copyrights in the
 * portions it created.
 * 
 * This file, and the files included with this file, is distributed
 * and made available on an 'AS IS' basis, WITHOUT WARRANTY OF ANY
 * KIND, EITHER EXPRESS OR IMPLIED, AND REALNETWORKS HEREBY DISCLAIMS
 * ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET
 * ENJOYMENT OR NON-INFRINGEMENT.
 * 
 * Technology Compatibility Kit Test Suite(s) Location:
 *    http://www.helixcommunity.org/content/tck
 * 
 * Contributor(s):
 * 
 * ***** END LICENSE BLOCK ***** */

#include "platform/symbian/hxsymbianapman.h"
#include "ihxpckts.h"

#include "debug.h"
#define D_AP_MANAGER 0x20000000

const UINT32 DefaultNumOfRetries = 1; /* Number of connect retries before
				       * reporting the error. The retry
				       * mechanism is needed because switching
				       * access points can cause the first
				       * connect to fail. This is a documented
				       * Symbian bug.
				       */


class HXSymbianAPManAO : public CActive
{
public:
    HXSymbianAPManAO(HXSymbianAccessPointManager* pParent,
		     CIntConnectionInitiator* pConnInit);
    ~HXSymbianAPManAO();

    HX_RESULT Connect(UINT32 ulAccessPointId);

    HX_RESULT Disconnect();

    void RunL();
    void DoCancel();

private:
    HXSymbianAccessPointManager* m_pParent;
    CIntConnectionInitiator* m_pConnInit;
    CCommsDbConnectionPrefTableView::TCommDbIapConnectionPref m_connPref;
    BOOL m_bConnecting;
};

HXSymbianAPManAO::HXSymbianAPManAO(HXSymbianAccessPointManager* pParent,
				   CIntConnectionInitiator* pConnInit) :
    CActive(EPriorityStandard),
    m_pParent(pParent),
    m_pConnInit(pConnInit),
    m_bConnecting(FALSE)
{
    CActiveScheduler::Add(this);
}

HXSymbianAPManAO::~HXSymbianAPManAO()
{
    if (IsActive())
    {
	Cancel();
    }
    
    m_pParent = 0;
    m_pConnInit = 0;
}

HX_RESULT HXSymbianAPManAO::Connect(UINT32 ulAccessPointId)
{
    HX_RESULT res = HXR_UNEXPECTED;

    if (m_pConnInit && !IsActive())
    {
	TInt theErr = KErrNone;

	m_bConnecting = TRUE;
	iStatus = KRequestPending;

	m_connPref.iRanking = 1; // Means always try this pref
	m_connPref.iDirection = ECommDbConnectionDirectionOutgoing;
	m_connPref.iDialogPref = ECommDbDialogPrefDoNotPrompt;
	m_connPref.iBearer.iBearerSet = (ECommDbBearerGPRS | ECommDbBearerCSD);
	m_connPref.iBearer.iIapId = ulAccessPointId;
	
	TRAP(theErr, m_pConnInit->ConnectL(m_connPref, iStatus));
	
	if (KErrNone == theErr)
	{
	    SetActive();
	    res = HXR_OK;
	}
	else
	{
	    res = HXR_NET_CONNECT;
	}
    }

    return res;
}

HX_RESULT HXSymbianAPManAO::Disconnect()
{
    HX_RESULT res = HXR_FAILED;

    if (m_pConnInit && !IsActive())
    {
	m_bConnecting = FALSE;
	iStatus = KRequestPending;

	if (KErrNone == m_pConnInit->TerminateActiveConnection(iStatus))
	{
	    SetActive();
	    res = HXR_OK;
	}
    }

    return res;
}

void HXSymbianAPManAO::RunL()
{
    if (m_pParent)
    {
	HX_RESULT status = HXR_NET_CONNECT;
	
	if (m_bConnecting)
	{
	    if ((iStatus == KErrNone) ||
		(iStatus == KConnectionPref1Exists) ||
		(iStatus == KConnectionExists) ||
		(iStatus == KConnectionPref1Created) ||
		(iStatus == KConnectionCreated) ||
		(iStatus == KErrOutstandingRequest))
	    {
		status = HXR_OK;
	    }

	    m_pParent->ConnectDone(status);
	}
	else 
	{
	    if ((iStatus == KErrNone) ||
		(iStatus == KConnectionTerminated) ||
		(iStatus == KErrOutstandingRequest))
	    {
		status = HXR_OK;
	    }

	    m_pParent->DisconnectDone(status);
	}
    }
}

void HXSymbianAPManAO::DoCancel()
{
    // Cancel possible outstanding request 
    if(m_pConnInit && m_pConnInit->IsActive())
    {
        m_pConnInit->Cancel();
    }
}

BEGIN_INTERFACE_LIST(HXSymbianAccessPointManager)
    INTERFACE_LIST_ENTRY_SIMPLE(IHXAccessPointManager)
    INTERFACE_LIST_ENTRY_SIMPLE(IHXAccessPointSelectorResponse)
END_INTERFACE_LIST

HXSymbianAccessPointManager::HXSymbianAccessPointManager():
    m_state(apError),
    m_pConnInit(0),
    m_pConnector(0),
    m_pPreferredInfo(NULL),
    m_pCCF(NULL),
    m_pAPSelector(NULL),
    m_bSelectAPPending(FALSE)
{
#ifdef _DEBUG
    debug_level() |= D_AP_MANAGER;
#endif /* _DEBUG */

    DPRINTF(D_AP_MANAGER, ("HXSymbianAccessPointManager::HXSymbianAccessPointManager()\n"));

    TRAPD(theErr, m_pConnInit = CIntConnectionInitiator::NewL());

    m_pConnector = new HXSymbianAPManAO(this, m_pConnInit);

    if (m_pConnInit && m_pConnector &&
	(KErrNone == m_sockServ.Connect()) &&
	(KErrNone == theErr))
    {
	m_state = apIdle;
    }
}

HXSymbianAccessPointManager::~HXSymbianAccessPointManager()
{
    DPRINTF(D_AP_MANAGER, ("HXSymbianAccessPointManager::~HXSymbianAccessPointManager()\n"));
    HX_DELETE(m_pConnector);
    HX_DELETE(m_pConnInit);

    HX_RELEASE(m_pPreferredInfo);
    HX_RELEASE(m_pCCF);
    HX_RELEASE(m_pAPSelector);

    m_sockServ.Close();

    DispatchConnectDones(HXR_FAILED);
}
/*
 * IHXAccessPointManager methods
 */

/************************************************************************
 *	Method:
 *	    IHXAccessPointManager::Connect
 *	Purpose:
 *	    Notifies the access point manager that an object wants the access
 *      point to connect to it's ISP.
 *
 */
STDMETHODIMP
HXSymbianAccessPointManager::Connect(THIS_ IHXAccessPointConnectResponse* pResp)
{
    DPRINTF(D_AP_MANAGER, ("HXSymbianAccessPointManager::Connect()\n")); 

    HX_RESULT res = HXR_FAILED;

    if (pResp)
    {
	res = DoConnect(pResp);
    }
    
    return res;
}

/************************************************************************
 *	Method:
 *	    IHXAccessPointManager::RegisterSelector
 *	Purpose:
 *      Provides the IHXAccessPointManager with an IHXAccessPointSelector 
 *      to use when it needs information about the desired access point.
 *
 */
STDMETHODIMP 
HXSymbianAccessPointManager::RegisterSelector(THIS_ IHXAccessPointSelector* pSelector)
{
    HX_RESULT res = HXR_FAILED;

    // Currently we only support 1 registered selector so
    // we only allow this call to succeed if m_pAPSelector
    // is not set.

    if (pSelector && !m_pAPSelector)
    {
	m_pAPSelector = pSelector;
	m_pAPSelector->AddRef();

	res = HXR_OK;
    }

    return res;
}
    
/************************************************************************
 *	Method:
 *	    IHXAccessPointManager::UnregisterSelector
 *	Purpose:
 *      Unregisters a previously registered IHXAccessPointSelector
 *
 */
STDMETHODIMP
HXSymbianAccessPointManager::UnregisterSelector(THIS_ IHXAccessPointSelector* pSelector) 
{
    HX_RESULT res = HXR_FAILED;

    // We only allow one registered selector so this call
    // will only succeed if the pSelector is a valid pointer
    // and matches the selector that was registered.

    if (pSelector && (pSelector == m_pAPSelector))
    {
	HX_RELEASE(m_pAPSelector);
    }

    return res;
}
    
/************************************************************************
 *	Method:
 *	    IHXAccessPointManager::GetActiveAccessPointInfo
 *	Purpose:
 *      Returns information about the access point we are currently 
 *      connected to. This function returns an error if we are 
 *      not connected to an access point.
 *
 */
STDMETHODIMP
HXSymbianAccessPointManager::GetActiveAccessPointInfo(THIS_ REF(IHXValues*) pInfo)
{
    HX_RESULT res = HXR_UNEXPECTED;

    pInfo = NULL;

    if (m_pCCF)
    {
	ULONG32 ulActiveID = 0;
	
	res = GetActiveID(ulActiveID);

	if (HXR_OK == res)
	{
	    res = m_pCCF->CreateInstance(CLSID_IHXValues, (void**)&pInfo);
	    
	    if (HXR_OK == res)
	    {
		res = pInfo->SetPropertyULONG32("ID", ulActiveID);
		
		if (HXR_OK != res)
		{
		    HX_RELEASE(pInfo);
		}
	    }
	}
    }

    DPRINTF(D_AP_MANAGER, 
	    ("HXSymbianAccessPointManager::GetActiveAccessPointInfo() : %08x\n",
	     res));
    
    return res;

}

/************************************************************************
 *	Method:
 *	    IHXAccessPointManager::GetPreferredAccessPointInfo
 *	Purpose:
 *      Returns information about the access point we want to connect to.
 */
STDMETHODIMP
HXSymbianAccessPointManager::GetPreferredAccessPointInfo(THIS_ REF(IHXValues*) pInfo)
{
    HX_RESULT res = HXR_FAILED;

    pInfo = m_pPreferredInfo;

    if (pInfo)
    {
	res = HXR_OK;
    }

    DPRINTF(D_AP_MANAGER, 
	    ("HXSymbianAccessPointManager::GetPreferredAccessPointInfo() : %08x\n",
	     res));

    return res;
}

/************************************************************************
 *	Method:
 *	    IHXAccessPointManager::SetPreferredAccessPointInfo
 *	Purpose:
 *      Tells the access point manager about the access 
 *      point we would like it to connect to.
 */
STDMETHODIMP
HXSymbianAccessPointManager::SetPreferredAccessPointInfo(THIS_ IHXValues* pInfo)
{
    HX_RESULT res = HXR_FAILED;
    ULONG32 ulAccessPointID = 0;

    if (pInfo && (HXR_OK == pInfo->GetPropertyULONG32("ID", ulAccessPointID)))
    {
	HX_RELEASE(m_pPreferredInfo);

	m_pPreferredInfo = pInfo;
	m_pPreferredInfo->AddRef();

	res = HXR_OK;
    }
    else
    {
	HX_RELEASE(m_pPreferredInfo);
    }

    return res;
}

/*
 * IHXAccessPointSelectorResponse methods
 */

/************************************************************************
 *	Method:
 *	    IHXAccessPointSelectorResponse::SelectAccessPointDone
 *	Purpose:
 *      Returns the selected access point info
 */
STDMETHODIMP
HXSymbianAccessPointManager::SelectAccessPointDone(THIS_ HX_RESULT status, 
						   IHXValues* pInfo)
{
    HX_RESULT res = HXR_UNEXPECTED;

    if (m_bSelectAPPending)
    {
	m_bSelectAPPending = FALSE;

	if ((HXR_OK == status) &&
	    (HXR_OK == SetPreferredAccessPointInfo(pInfo)))
	{
	    status = DoConnect(0);
	}

	if (HXR_OK != status)
	{
	    if (HXR_OUTOFMEMORY != status)
	    {
		status = HXR_NET_CONNECT;
	    }

	    DispatchConnectDones(status);
	}

	res = HXR_OK;
    }

    return res;
}

void HXSymbianAccessPointManager::SetContext(IUnknown* pContext)
{
    if (pContext)
    {
	pContext->QueryInterface(IID_IHXCommonClassFactory, (void**)&m_pCCF);
    }
}

HX_RESULT 
HXSymbianAccessPointManager::DoConnect(IHXAccessPointConnectResponse* pResp)
{
    DPRINTF(D_AP_MANAGER, ("HXSymbianAccessPointManager::DoConnect(%p)\n", 
			   pResp));

    HX_RESULT res = HXR_FAILED;

    ULONG32 ulActiveId = 0;
    ULONG32 ulPreferredId = 0;

    BOOL bQueueResponse = (pResp) ? TRUE : FALSE;

    if (HXR_OK == GetPreferredID(ulPreferredId))
    {
	// We have a preferred access point set

	if (HXR_OK != GetActiveID(ulActiveId))
	{
	    // We don't have an active access point

	    if (apConnected == m_state)
	    {
		// The access point disconnected without
		// our knowledge. Update our state.
		m_state = apIdle;
	    }

	    // Start to connect
	    res = StartConnection();
	}
	else if (ulActiveId == ulPreferredId)
	{
	    // We have a preferred access point and we are connected
	    // to it.

	    // Dispatch the callbacks now.
	    if (pResp)
	    {
		pResp->ConnectDone(HXR_OK);
		bQueueResponse = FALSE;
	    }
	
	    if (apIdle == m_state)
	    {
		m_state = apConnected;

		// Dispatch any other pending callbacks
		DispatchConnectDones(HXR_OK);
	    }
	    
	    res = HXR_OK;
	}
	else
	{
	    // We need to disconnect from the current access
	    // point
	    
	    res = StartDisconnect();
	}
    }
    else
    {
	// We don't have a preferred access point

	if (m_pAPSelector)
	{
	    if (!m_bSelectAPPending)
	    {
		// Use the Selector to get the preferred access point

		m_bSelectAPPending = TRUE;
		res = m_pAPSelector->SelectAccessPoint(this);

		if (HXR_OK != res)
		{
		    m_bSelectAPPending = FALSE;
		}
	    }
	    else
	    {
		// A SelectAccessPoint() request is currently
		// pending
		res = HXR_OK;
	    }
	}
	else
	{
	    // We have no way to get access point information.
	    res = HXR_NET_CONNECT;
	}
    }

    if ((HXR_OK == res) && bQueueResponse)
    {
	pResp->AddRef();
	m_respList.AddTail(pResp);
    }

    return res;
}

HX_RESULT HXSymbianAccessPointManager::StartConnection()
{
    DPRINTF(D_AP_MANAGER, ("HXSymbianAccessPointManager::StartConnection()\n"));

    HX_RESULT res = HXR_UNEXPECTED;
    BOOL bConnect = TRUE;

    if (apIdle == m_state)
    {
	m_ulRetryCount = DefaultNumOfRetries;
    }
    else if (apConnecting != m_state)
    {
	bConnect = FALSE;
    }

    if (bConnect && m_pPreferredInfo)
    {
	ULONG32 ulAccessPointID = 0;
	res = m_pPreferredInfo->GetPropertyULONG32("ID", ulAccessPointID);

	if (HXR_OK == res)
	{
	    res = m_pConnector->Connect(ulAccessPointID);

	    if (HXR_OK == res)
	    {
		m_state = apConnecting;
	    }
	}
    }

    DPRINTF(D_AP_MANAGER, 
	    ("HXSymbianAccessPointManager::StartConnection() : res %08x\n",
	     res));

    return res;
}

void HXSymbianAccessPointManager::ConnectDone(HX_RESULT status)
{
    DPRINTF(D_AP_MANAGER, 
	    ("HXSymbianAccessPointManager::ConnectDone(%08x)\n",
	     status));

    HX_ASSERT(apConnecting == m_state);

    BOOL bReportStatus = TRUE;

    if (HXR_OK == status)
    {
	m_state = apConnected;
    }
    else if (m_ulRetryCount)
    {
	// Sometimes the first connect fails if we
	// disconnect from an access point and then
	// connect to a different one. This is a
	// documented Symbian bug.

	// Try to connect again
	m_ulRetryCount--;

	status = StartConnection();

	if (HXR_OK == status)
	{
	    bReportStatus = FALSE;
	}
    }
    else
    {
	// Connect and all retries failed.
	// Transition back to the idle state
	m_state = apIdle;
    }

    if (bReportStatus)
    {
	DispatchConnectDones(status);
    }
}

HX_RESULT HXSymbianAccessPointManager::StartDisconnect()
{
    DPRINTF(D_AP_MANAGER, ("HXSymbianAccessPointManager::StartDisconnect()\n"));

    HX_RESULT res = HXR_FAILED;
    
    if (HXR_OK == m_pConnector->Disconnect())
    {
	m_state = apDisconnecting;
	res = HXR_OK;
    }

    DPRINTF(D_AP_MANAGER, 
	    ("HXSymbianAccessPointManager::StartDisconnect() : res %08x\n",
	     res));

    return res;

}

void HXSymbianAccessPointManager::DisconnectDone(HX_RESULT status)
{
    DPRINTF(D_AP_MANAGER, 
	    ("HXSymbianAccessPointManager::DisconnectDone(%08x)\n",
	     status));

    HX_ASSERT(apDisconnecting == m_state);

    m_state = apIdle;

    if (HXR_OK == status)
    {
	// Try to connect now
	status = DoConnect(0);
    }
    
    if (HXR_OK != status)
    {
	// We failed to reconnect. Send the
	// failure code to the response objects
	DispatchConnectDones(status);
    }
}

void HXSymbianAccessPointManager::DispatchConnectDones(HX_RESULT status)
{
    DPRINTF(D_AP_MANAGER, 
	    ("HXSymbianAccessPointManager::DispatchConnectDones(%08x)\n",
	     status));

    // Handle any pending connect requests
    while(!m_respList.IsEmpty())
    {
	IHXAccessPointConnectResponse* pResp = 
	    (IHXAccessPointConnectResponse*)m_respList.RemoveHead();

	pResp->ConnectDone(status);
	HX_RELEASE(pResp);
    }
}

HX_RESULT HXSymbianAccessPointManager::GetPreferredID(REF(ULONG32) ulID)
{
    HX_RESULT res = HXR_FAILED;

    if (m_pPreferredInfo)
    {
	res = m_pPreferredInfo->GetPropertyULONG32("ID", ulID);
    }

    return res;
}

HX_RESULT HXSymbianAccessPointManager::GetActiveID(REF(ULONG32) ulID)
{
    HX_RESULT res = HXR_FAILED;

    TUint32 aIAPId = 0;
    if (m_pConnInit && (KErrNone == m_pConnInit->GetActiveIap(aIAPId)))
    {
	ulID = aIAPId;
	res = HXR_OK;
    }

    return res;
}
