#include "qgnetworkinterface.h"

#include <QHostInfo>
#include <QNetworkInterface>

#include <QDebug>

static QHostAddress qgHostAddress=QHostAddress::LocalHost;
static QHostAddress qgBroadcastAddress=QHostAddress::LocalHost;

static unsigned int adapter_index;

static QHostAddress selectDefaultInterface()
{
    QList<QNetworkInterface> hal=QNetworkInterface::allInterfaces();
    if (hal.isEmpty())
    {
      qDebug()<<"Network Config: NO HOST ADDRESSES";
      return QHostAddress();
    }
    else
    {
      foreach(QNetworkInterface nif, hal)
      {
        //QList<QHostAddress> nhal=nif.allAddresses();
        QList<QNetworkAddressEntry> nhal=nif.addressEntries();
        foreach(QNetworkAddressEntry aentry, nhal)
        {
          QHostAddress a=aentry.ip();

          if (a.toString().startsWith("192.168"))
          {
                  adapter_index=nif.index();
                  return aentry.ip();
          }
        }
      }

      foreach(QNetworkInterface nif, hal)
      {
        //QList<QHostAddress> nhal=nif.allAddresses();
        QList<QNetworkAddressEntry> nhal=nif.addressEntries();
        foreach(QNetworkAddressEntry aentry, nhal)
        {
          QHostAddress a=aentry.ip();

          if (a.toString().startsWith("169.254"))
          {
                  adapter_index=nif.index();
                  return aentry.ip();
          }
        }
      }
      return QHostAddress();
    }
}

void QgNetworkInterface::setNetworkInterface(const QHostAddress& adr)
{
   qgHostAddress=adr;
   quint32 ip=adr.toIPv4Address();
   if (!adr.isLoopback())
    ip|=255;

   qgBroadcastAddress=QHostAddress(ip);
   qDebug()<<"QgNetworkInterface:"<<adr;
}

QHostAddress QgNetworkInterface::networkInterface()
{
    return qgHostAddress;
}

QHostAddress QgNetworkInterface::networkBroadcast()
{
    return qgBroadcastAddress;
}

QString QgNetworkInterface::networkIP()
{
    return qgHostAddress.toString();
}

void QgNetworkInterface::setNetworkIP(const QString& str)
{
    qgHostAddress=QHostAddress(str);
}

unsigned int QgNetworkInterface::networkMTU()
{
    return 1536;
}
void QgNetworkInterface::setNetworkMTU(unsigned int)
{
    return;
}

unsigned int QgNetworkInterface::networkUdpMTU()
{
    return networkMTU()-(20+8);
}

QString QgNetworkInterface::hostName()
{
    return QHostInfo::localHostName();
}

unsigned int QgNetworkInterface::adapterIndex()
{
    return adapter_index;
}

void QgNetworkInterface::initializeDefaultInterface()
{
    setNetworkInterface(selectDefaultInterface());
}
