#include "qgnetworkconnectiondialog.h"
#include "ui_qgnetworkconnectiondialog.h"

#include <QHostAddress>
#include <QHostInfo>
#include <QNetworkInterface>
#include <QNetworkAddressEntry>

#include "mydebug.h"

QgNetworkConnectionDialog::QgNetworkConnectionDialog(const QString& prefered_net, QWidget *parent) :
  QDialog(parent),
  ui(new Ui::QgNetworkConnectionDialog),
  preferedNetwork("127."),
  privateSubnet(false)
{
  ui->setupUi(this);

  unsigned int prefered_index=0;
  privateSubnet=false;

  if (!prefered_net.isEmpty())
      preferedNetwork=prefered_net;

  QHostInfo hi=QHostInfo::fromName(QHostInfo::localHostName());
  ui->groupBox->setTitle(QString("Host: %1").arg(hi.hostName()));
  //QList<QHostAddress> hal=hi.addresses();
  QList<QNetworkInterface> hal=QNetworkInterface::allInterfaces();
  if (hal.isEmpty())
  {
    MyDebug.logMsg( type_log_error, origin_msg_generic ,"Network Config: NO HOST ADDRESSES");
    ui->comboBoxInterface->addItem("<No Interface>");
    ui->comboBoxInterface->setEnabled(false);
  }
  else
  {
    foreach(QNetworkInterface nif, hal)
    {
      //QList<QHostAddress> nhal=nif.allAddresses();
      QList<QNetworkAddressEntry> nhal=nif.addressEntries();
      foreach(QNetworkAddressEntry aentry, nhal)
      {
        bool private_subnet=false;

        QHostAddress a=aentry.ip();

        if (!(a.toString().startsWith("192.168") ||
              a.toString().startsWith("169.254") ||
              a.toString().startsWith("127.")))
            continue;

        ui->comboBoxInterface->addItem(QString("%1 (%2) [%3]").arg(nif.humanReadableName()).arg(a.toString()).arg(nif.index()), a.toString());
        int currentIndex=ui->comboBoxInterface->count()-1;
        //if (a.toString().startsWith("192.168.0") ||a.toString().startsWith("192.168.2"))
        if (a.toString().startsWith(preferedNetwork))
        {
          prefered_index=currentIndex;
          private_subnet=true;
          privateSubnet=privateSubnet;
        }
        ui->comboBoxInterface->setItemData(currentIndex, private_subnet, Qt::UserRole+1);
        ui->comboBoxInterface->setItemData(currentIndex, nif.index(), Qt::UserRole+2);

        //ui->comboBoxInterface->seIif (nif.flags() & QNetworkInterface::IsUp)
      }
    }
    if (prefered_index)
      ui->comboBoxInterface->setCurrentIndex(prefered_index);
  }
#if 0
  if (privateSubnet)
  {
    ui->spinBoxDsp1Address->setMinimum(128);
    ui->spinBoxDsp1Address->setMaximum(250);
    ui->spinBoxDsp1Address->setValue(128);
  }
  else
  {
    ui->spinBoxDsp1Address->setMinimum(1);
    ui->spinBoxDsp1Address->setMaximum(250);
    ui->spinBoxDsp1Address->setValue(100);
  }
#endif
  ui->comboBoxJumbo->addItem("NO", 0);
  ui->comboBoxJumbo->addItem("2K", 2*1024);
  ui->comboBoxJumbo->addItem("3K", 3*1024);
  ui->comboBoxJumbo->addItem("4K", 4*1024);
  ui->comboBoxJumbo->addItem("8K", 8*1024);
  for(int w=0; w<12; ++w)
  {
    int wsize=w==0 ? 0 : 1<<(w-1);
    QString str=QString("%1").arg(wsize);
    ui->comboBoxRxWin->addItem(str, wsize);
    if (wsize==512)
      ui->comboBoxRxWin->setCurrentIndex(ui->comboBoxRxWin->count()-1);
    ui->comboBoxTxWin->addItem(str, wsize);
    if (wsize==512)
      ui->comboBoxTxWin->setCurrentIndex(ui->comboBoxTxWin->count()-1);
  }

  //ui->gbNetSettings->layout()->setEnabled(false);
  connect(ui->gbNetSettings, &QGroupBox::toggled, this,
          [this](bool on)
          {
            //ui->gbNetSettings->layout()->setEnabled(on);
            ui->gbNetSettings->setMaximumHeight(on ? 1000 : 24);
          }
    );

  connect(ui->comboBoxInterface, SIGNAL(currentIndexChanged(int)), SLOT(hostInterfaceChanged(int)));
}

//void QgNetworkConnectionDialog::setPreferedNetwork(const QString& net)
//{
//   preferedNetwork=net;
//}

QString QgNetworkConnectionDialog::hostNetworkName() const
{
    return ui->comboBoxInterface->itemText(ui->comboBoxInterface->currentIndex());
}

QString QgNetworkConnectionDialog::hostAddress() const
{
  //return ui->comboBoxInterface->currentText();
  return ui->comboBoxInterface->itemData(ui->comboBoxInterface->currentIndex()).toString();
}


unsigned int QgNetworkConnectionDialog::adapterIndex() const
{
   return ui->comboBoxInterface->itemData(ui->comboBoxInterface->currentIndex(), Qt::UserRole+2).toUInt();
}

QString QgNetworkConnectionDialog::targetAddress(int /*n*/) const
{
  QHostAddress h(ui->comboBoxInterface->itemData(ui->comboBoxInterface->currentIndex()).toString());
  quint32 v=h.toIPv4Address();
  v=v & 0xFFFFFF00;
  //v=v | ((unsigned int)(ui->spinBoxDsp1Address->value()) & 0x00FF);
  h.setAddress(v);
  return h.toString();
}

void QgNetworkConnectionDialog::hostInterfaceChanged(int /*n*/)
{
#if 0
  bool private_subnet=ui->comboBoxInterface->itemData(n, Qt::UserRole+1).toBool();
  if (!private_subnet)
  {
    ui->spinBoxDsp1Address->setMinimum(128);
    ui->spinBoxDsp1Address->setMaximum(250);
  }
  else
  {
    ui->spinBoxDsp1Address->setMinimum(1);
    ui->spinBoxDsp1Address->setMaximum(254);
  }
#endif
}

int QgNetworkConnectionDialog::jumboFrame() const
{
  return ui->comboBoxJumbo->itemData(ui->comboBoxJumbo->currentIndex()).toInt();
}

int QgNetworkConnectionDialog::txWindow() const
{
  return ui->comboBoxTxWin->itemData(ui->comboBoxTxWin->currentIndex()).toInt();
}

int QgNetworkConnectionDialog::rxWindow() const
{
  return ui->comboBoxRxWin->itemData(ui->comboBoxRxWin->currentIndex()).toInt();
}

void QgNetworkConnectionDialog::addWidget(QWidget* w)
{
    ui->extLayout->addWidget(w);
}

QgNetworkConnectionDialog::~QgNetworkConnectionDialog()
{
  delete ui;
}
