#include "AddIpEntryDialog.h"
#include "ui_AddIpEntryDialog.h"
#include <QRegExpValidator>
#include <QPushButton>

AddIpEntryDialog::AddIpEntryDialog(QWidget *parent, bool permVisible) :
    QDialog(parent),
    ui(new Ui::AddIpEntryDialog) {

    ui->setupUi(this);
    QString ipNumReg = "(25\\d|2[0-4]{1,1}\\d|[0-1]{0,1}\\d{1,2}|\\d{1,2}){1,1}";
    ui->ipAddrEdit->setValidator(new QRegExpValidator(
                                     QRegExp( ipNumReg + "\\." + ipNumReg + "\\."
                                              + ipNumReg + "\\." + ipNumReg), this));
    connect(ui->ipAddrEdit, SIGNAL(textChanged(QString)), SLOT(ipTextChanged(QString)));

    ui->permanentCheck->setVisible(permVisible);
    ipTextChanged(ui->ipAddrEdit->text());
    setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
}

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

QHostAddress AddIpEntryDialog::addr() const {
    return QHostAddress(ui->ipAddrEdit->text());
}

bool AddIpEntryDialog::autocon() const {
    return ui->autoCheck->isChecked();
}

bool AddIpEntryDialog::reconnect() const {
    return ui->reconnectCheck->isChecked();
}

bool AddIpEntryDialog::needConnect() const {
    return ui->connectCheck->isChecked();
}

bool AddIpEntryDialog::permanent() const {
    return ui->permanentCheck->isChecked();
}

void AddIpEntryDialog::ipTextChanged(QString text) {
    int pos = 0;
    QPushButton* okBtn = ui->buttonBox->button(QDialogButtonBox::Ok);
    if (ui->ipAddrEdit->validator()->validate(text, pos) == QValidator::Acceptable) {
        ui->ipAddrEdit->setStyleSheet("QLineEdit { color: darkGreen }");
        okBtn->setEnabled(true);
    } else {
        ui->ipAddrEdit->setStyleSheet("QLineEdit { color: darkRed }");
        okBtn->setEnabled(false);
    }
}
