#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    ui->frameClient->setVisible(false);
    ui->frameServer->setVisible(false);
    ui->frameSend->setVisible(false);
    ui->lwText->setVisible(false);
    server = new Server();
    client = new Client();
    ui->cbIPList->addItems(server->getIpList());
    startTimer(40);
}


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


void Widget::timerEvent(QTimerEvent *)
{
    ui->serverStatus->setText(server->getStatus());
    ui->clienStatus->setText(client->getStatus());
}


void Widget::on_bpSetServer_clicked()
{
    ui->frameServer->setVisible(true);
    ui->lwText->setVisible(true);
    ui->frameMain->setVisible(false);
//    ui->frameSend->setVisible(true);
    connect(server,SIGNAL(receiveData(QByteArray)),this,SLOT(onReceive(QByteArray)));
}


void Widget::on_bpStartServer_clicked()
{
    server->startServer(QHostAddress(ui->cbIPList->currentText()));
}


void Widget::on_pbStopServer_clicked()
{
    server->stopServer();
}


void Widget::on_pbSetClient_clicked()
{
    ui->frameClient->setVisible(true);
    ui->lwText->setVisible(true);
    ui->frameMain->setVisible(false);
    ui->frameSend->setVisible(true);
    connect(client,SIGNAL(receive(QByteArray)),this,SLOT(onReceive(QByteArray)));
}


void Widget::on_pbConnect_clicked()
{
    client->connectToServer(QHostAddress(ui->leIP->text()));
}


void Widget::on_pbDisconnect_clicked()
{
    client->closeConnection();
}


void Widget::onReceive(QByteArray ba)
{
    ui->lwText->addItem(QString::fromUtf8(ba.data(),ba.size()));
}


void Widget::on_bpSend_clicked()
{
    QByteArray ba = ui->leText->text().toUtf8();
    client->send(ba);
}


void Widget::on_leText_returnPressed()
{
    on_bpSend_clicked();
}
