/*
* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors:
*
* Description: 
*
*/

#ifndef QSYM_IAP_UTIL_H
#define QSYM_IAP_UTIL_H

#include <es_sock.h>
#include <sys/socket.h>
#include <net/if.h>
#include <rconnmon.h>

QString qt_TDesC2QStringL(const TDesC& aDescriptor) 
{
#ifdef QT_NO_UNICODE
    return QString::fromLocal8Bit(aDescriptor.Ptr(), aDescriptor.Length());
#else
    return QString::fromUtf16(aDescriptor.Ptr(), aDescriptor.Length());
#endif
}

static void qt_SetDefaultIapL() 
{
    TUint count;
    TRequestStatus status;
    TUint ids[15];

    RSocketServ serv;
    CleanupClosePushL(serv);

    RConnection conn;
    CleanupClosePushL(conn);

    RConnectionMonitor monitor;
    CleanupClosePushL(monitor);

    monitor.ConnectL();
    monitor.GetConnectionCount(count, status);
    User::WaitForRequest(status);
    if(status.Int() != KErrNone) {
        User::Leave(status.Int());
    }

    TUint numSubConnections;

    if(count > 0) {
        for (TInt i = 1; i <= count; i++) {
            User::LeaveIfError(monitor.GetConnectionInfo(i, ids[i-1], numSubConnections));
        }
        /*
         * get IAP value for first active connection
         */
        TBuf< 50 > iapName;
        monitor.GetStringAttribute(ids[0], 0, KIAPName, iapName, status);
        User::WaitForRequest(status);
        if (status.Int() != KErrNone) {
            User::Leave(status.Int());
        } else {
            QString strIapName = qt_TDesC2QStringL(iapName);
            struct ifreq ifReq;
            strcpy(ifReq.ifr_name, strIapName.toLatin1().data());
            User::LeaveIfError(setdefaultif(&ifReq));
        }
    } else {
        /*
         * no active connections yet
         * use IAP dialog to select one
         */
        User::LeaveIfError(serv.Connect());
        User::LeaveIfError(conn.Open(serv));
        User::LeaveIfError(conn.Start());

        _LIT(KIapNameSetting, "IAP\\Name");
        TBuf8<50> iap8Name;
        User::LeaveIfError(conn.GetDesSetting(TPtrC(KIapNameSetting), iap8Name));
        iap8Name.ZeroTerminate();

        conn.Stop();

        struct ifreq ifReq;
        strcpy(ifReq.ifr_name, (char*)iap8Name.Ptr());
        User::LeaveIfError(setdefaultif(&ifReq));
    }
    CleanupStack::PopAndDestroy(&monitor);
    CleanupStack::PopAndDestroy(&conn);
    CleanupStack::PopAndDestroy(&serv);
}

static int qt_SetDefaultIap()
{
    TRAPD(err, qt_SetDefaultIapL());
    return err;
}

#endif // QSYM_IAP_UTIL_H
