/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/

#include <qstring.h>

#include "kwirelessmonitor.h"
#include "interfacemonitor.h"
#include "wm_arch.h"

InterfaceMonitor::InterfaceMonitor(const QString& ifName)
{
    mIFName = ifName;
    mIFStats.ESSID = "";
    mIFStats.quality = -1;
    mIFStats.bitrate = -1;
    mIFSocket = wm_openIFSocket(mIFName.ascii());
    
    initializeBitrateLists();
}

InterfaceMonitor::~InterfaceMonitor()
{
    wm_closeIFSocket(mIFSocket);
}

void InterfaceMonitor::setInterface(const QString& ifName)
{
    if (mIFName.compare(ifName) == 0) {
        return;
    }
    wm_closeIFSocket(mIFSocket);
    mIFName = ifName;
    if (ifName.isEmpty()) {
        mIFSocket = -1;
    } else {
        mIFSocket = wm_openIFSocket(mIFName.ascii());
        initializeBitrateLists();
    }
}

const struct wirelessStats *InterfaceMonitor::getStats()
{
    if (mIFSocket < 0) {
        mIFStats.ESSID = "";
        mIFStats.quality = -1;
        mIFStats.bitrate = -1;
        return &mIFStats;
    }

    /* Get ESSID */
    char essid[64];
    wm_getESSID(mIFSocket, mIFName.ascii(), essid, 64);
    mIFStats.ESSID = essid;
    
    /* Get bit rate */
    mIFStats.bitrate = wm_getBitrate(mIFSocket, mIFName.ascii());

    /* Get the current quality */
    mIFStats.quality = wm_getQuality(mIFSocket, mIFName.ascii());

    /* Get power management mode */
    mIFStats.powermgmt = wm_getPowerMgmt(mIFSocket, mIFName.ascii());

    return &mIFStats;
}

void InterfaceMonitor::getTransferBytes(unsigned long long *rx_bytes,
                                        unsigned long long *tx_bytes)
{
    wm_getTransferBytes(mIFName.ascii(), rx_bytes, tx_bytes);
}

void InterfaceMonitor::initializeBitrateLists()
{
    availableBitrateList.clear();
    wm_getBitrateList(mIFSocket, mIFName.ascii(), availableBitrateList);

    availableBitrateStrList.clear();
    QValueList<int>::iterator it;
    for (it = availableBitrateList.begin();
            it != availableBitrateList.end(); ++it) {
        availableBitrateStrList.append(
            QString("%1 Mbps").arg(((double) *it) / 1000000.0, 0, 'f', 1));
    }

    numAvailableBitrates = availableBitrateList.size();
}
