#include "commandwidget.h"

#include "ui_commandwidget.h"

CommandWidget::CommandWidget(QWidget *parent)
    : QWidget(parent), ui(new Ui::CommandWidget) {
    ui->setupUi(this);
    ui->stopConnectionToolBtn->setDisabled(true);
    ui->settingToolBtn->setIcon(QIcon(":/images/settings.png"));
    ui->settingToolBtn->setText("通信设置");
    ui->settingToolBtn->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);

    udpSocket = new QUdpSocket(this);
    connect(&settingDlg, &CommunicationSettingDlg::sendErrorMessage, this,
            &CommandWidget::receiveMessageSlots);
}

CommandWidget::~CommandWidget() {
    delete ui;
    if (udpSocket) udpSocket->deleteLater();
}

void CommandWidget::on_settingToolBtn_clicked() {
    settingDlg.exec();
}

// 连接
void CommandWidget::on_startConnectionToolBtn_clicked() {
    ui->startConnectionToolBtn->setDisabled(true);
    if (!g_networkSettingInfo) return;
    int dataSourceType = g_networkSettingInfo->value("DataSource").toInt();
    QString groupName = "";
    switch (dataSourceType) {
        case 0:
            groupName = "LLink";
            break;
        case 1:
            groupName = "SATCOM1";
            break;
        case 2:
            groupName = "SATCOM2";
            break;
        default:
            break;
    }

    m_remoteIP =
        g_networkSettingInfo->value(groupName + "/remoteIP").toString();
    m_remotePort =
        g_networkSettingInfo->value(groupName + "/remotePort").toInt();
    int localPort =
        g_networkSettingInfo->value(groupName + "/localPort").toInt();
    QString localIP =
        g_networkSettingInfo->value(groupName + "/localIP").toString();

    if (dataSourceType == 0) {  // 组播
        emit startConnectionSignal(m_remoteIP, m_remotePort);
    } else {  // 单播
        emit startConnectionSignal(localIP, localPort);
    }

    ui->stopConnectionToolBtn->setDisabled(false);
}

// 断开
void CommandWidget::on_stopConnectionToolBtn_clicked() {
    ui->stopConnectionToolBtn->setDisabled(true);

    emit stopConnectionSignal();

    // ui->stopConnectionToolBtn->setDisabled(false);
    ui->startConnectionToolBtn->setDisabled(false);
}

void CommandWidget::receiveMessageSlots(QString message, int type) {
    emit sendErrorMessage(message, type);
}
