#include "AddLtrdConnectionDialog.h"
#include "ui_AddLtrdConnectionDialog.h"
#include <QValidator>
#include <QPushButton>

AddLtrdConnectionDialog::AddLtrdConnectionDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::AddLtrdConnectionDialog)
{
    ui->setupUi(this);
    ui->ipAddrLbl->setText(tr("Remote %1 IP address").arg(LTR_SERVICE_NAME));
    setWindowTitle(tr("New %1 connection addition").arg(LTR_SERVICE_NAME));


    QString ipNubReg = "(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( ipNubReg + "\\." + ipNubReg + "\\."
                                              + ipNubReg + "\\." + ipNubReg), this));
    connect(ui->ipAddrEdit, SIGNAL(textChanged(QString)), SLOT(ipTextChanged(QString)));
    connect(ui->remoteCheck, SIGNAL(toggled(bool)), SLOT(remoteCheckChanged()));
    remoteCheckChanged();
}

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

QHostAddress AddLtrdConnectionDialog::addr() const
{
    return ui->remoteCheck->isChecked() ? QHostAddress(ui->ipAddrEdit->text()) : QHostAddress(QHostAddress(QHostAddress::LocalHost));
}

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

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

bool AddLtrdConnectionDialog::remote() const
{
    return ui->remoteCheck->isChecked();
}

void AddLtrdConnectionDialog::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);
    }
}

void AddLtrdConnectionDialog::remoteCheckChanged()
{
    ui->ipAddrEdit->setEnabled(ui->remoteCheck->isChecked());
}
