#include "bluetoothwidgetModify.h"
#include <QApplication>
#include <QPalette>

ModifybluetoothWidget::ModifybluetoothWidget(QWidget *parent) : QWidget(parent)
{
    //开线程连接
    m_bbluetooththread = new bluetooththread();
    QObject::connect(m_bbluetooththread,SIGNAL(result(bool)),this,SLOT(bluetoothservice(bool)));

    initMemberVariables();
    initLayout();
    setBluetoothStatus();
    m_bbluetooththread->start();
}

ModifybluetoothWidget::~ModifybluetoothWidget()
{

}

void ModifybluetoothWidget::initMemberVariables()
{

    //提前初始化字符串国际化
    m_not_Connected = QObject::tr("Not connected");
    m_closed = QObject::tr("Closed");

    m_pbluetoothIconLabel = new QLabel();
    m_pbluetoothIconLabel->setFixedSize(24, 24);

    m_pbluetoothNameLabel = new QLabel();

    QFont ft;
    ft.setPixelSize(12);
    m_pbluetoothNameLabel->setFont(ft);
    m_pbluetoothNameLabel->setFixedHeight(18);
    m_pbluetoothNameLabel->setFixedWidth(68);
    setLabelText(m_not_Connected);

    QPalette palette;
    palette.setBrush(QPalette::WindowText, Qt::black);
    this->update();

    m_pbluetoothButton    = new BlueToolsLabel();

    m_pStyleNormal = new customstyle_switchNormalStatus("ukui-default");

    m_pHboxButtonLayout   = new QHBoxLayout();
    m_pHboxButtonLayout->setContentsMargins(0, 0, 0, 0);
    m_pHboxButtonLayout->setSpacing(0);

    this->setFixedSize(148, 56);
    this->setContentsMargins(0, 0, 0, 0);
    return;
}

/* 初始化布局 */
void ModifybluetoothWidget::initLayout()
{
    m_pHboxButtonLayout->addItem(new QSpacerItem(12, 4));
    m_pHboxButtonLayout->addWidget(m_pbluetoothIconLabel);
    m_pHboxButtonLayout->addItem(new QSpacerItem(8, 4));
    m_pHboxButtonLayout->addWidget(m_pbluetoothNameLabel);
    m_pHboxButtonLayout->addItem(new QSpacerItem(18, 4));
    m_pHboxButtonLayout->addWidget(m_pbluetoothButton);
    m_pHboxButtonLayout->addItem(new QSpacerItem(4, 1));
    this->setLayout(m_pHboxButtonLayout);
    return;
}

/* 初始化dbus接口 */
bool ModifybluetoothWidget::initBluetoothDbus()
{
    m_pServiceInterface = new QDBusInterface(KYLIN_BLUETOOTH_SERVER_NAME,
                                             KYLIN_BLUETOOTH_SERVER_PATH,
                                             KYLIN_BLUETOOTH_SERVER_INTERFACE,
                                             QDBusConnection::sessionBus());
    if (!m_pServiceInterface->isValid() || m_pServiceInterface == nullptr) {
        qDebug() << "dbus接口初始化失败";
        return false;
    }

    //更新数据
    handBlueToothData();

    //连接改变的信号
    QDBusConnection::sessionBus().connect(QString(KYLIN_BLUETOOTH_SERVER_NAME),
                                          QString(KYLIN_BLUETOOTH_SERVER_PATH),
                                          QString(KYLIN_BLUETOOTH_SERVER_INTERFACE),
                                          QString("devConnectStatusSignal"), this, SLOT(updateBluetoothStatus(QString,bool)));

    //连接移除信号
    QDBusConnection::sessionBus().connect(QString(KYLIN_BLUETOOTH_SERVER_NAME),
                                          QString(KYLIN_BLUETOOTH_SERVER_PATH),
                                          QString(KYLIN_BLUETOOTH_SERVER_INTERFACE),
                                          QString("devRemoveSignal"), this, SLOT(removeBluetoothStatus(QString)));

    return true;
}

void ModifybluetoothWidget::handBlueToothData()
{
    m_devAddress.clear();
    m_connectDevice.clear();
    m_devName.clear();

    QDBusReply<QStringList> reply = m_pServiceInterface->call("getDefaultAdapterPairedDevAddress");
    if (reply.isValid()) {
        m_devAddress = reply.value();
        qDebug()<<"获取蓝牙地址列表:" << m_devAddress;
        for (int i = 0 ;i < m_devAddress.count(); i++) {
            QDBusReply<bool> devStatus = m_pServiceInterface->call("getDevConnectStatus",m_devAddress.at(i));
            if (devStatus.value()) {
                qDebug()<<"有效蓝牙地址为："<<m_devAddress.at(i);
                QDBusReply<QString> devName = m_pServiceInterface->call("getDevName",m_devAddress.at(i));
                qDebug()<<"获取蓝牙名称："<< devName.value();
                m_devName.append(devName.value());
            } else {
                qDebug()<<"无效蓝牙地址为："<<m_devAddress.at(i) << "暂不获取蓝牙名称";
            }
        }
    } else {
        m_bbluetoothStatus = false;
        qDebug()<<"连接dbus失败，无设备连接";
    }

    if(m_devName.isEmpty()) {
        qDebug()<<"筛选的列表为空，无设备连接";
        m_bbluetoothStatus = false;
    } else {
        m_bbluetoothStatus = true;
        for (int i = 0 ;i < m_devName.count(); i++) {
            m_connectDevice = m_connectDevice + " " + m_devName.at(i);
        }
        qDebug()<<"最后整理的蓝牙列表:"<<m_connectDevice;
    }
}

/* 初始化第一次蓝牙状态 */
void ModifybluetoothWidget::initBluetoothStatus()
{
    //在连接上蓝牙dbus后，再连接相应的信号
    connect(m_pbluetoothButton, &BlueToolsLabel::LabelClicked, this, &ModifybluetoothWidget::setButtonclickSlots);
    setBluetoothStatus();
    if (m_bbluetoothStatus) {
        setLabelText(m_connectDevice);
    } else {
        setLabelText(m_not_Connected);
    }
}

/* 根据按钮状态设置背景色 */
void ModifybluetoothWidget::setBluetoothStatus()
{
    if (m_bbluetoothStatus) {
        m_pbluetoothIconLabel->setPixmap((QIcon::fromTheme(KYLIN_BLUETOOTH_PRESS_NAME, QIcon(KYLIN_BLUETOOTH_PRESS_PATH))).pixmap(m_pbluetoothIconLabel->size()));
        setLabelText(m_not_Connected);
    } else {
        m_pbluetoothIconLabel->setPixmap((QIcon::fromTheme(KYLIN_BLUETOOTH_NORMAL_NAME, QIcon(KYLIN_BLUETOOTH_NORMAL_PATH))).pixmap(m_pbluetoothIconLabel->size()));
        setLabelText(m_closed);
    }
    return;
}

/* 更新蓝牙状态 */
void ModifybluetoothWidget::updateBluetoothStatus(QString arg, bool status)
{
    qDebug()<<"更新蓝牙状态";
    handBlueToothData();
    initBluetoothStatus();
}

/* 移除信号 */
void ModifybluetoothWidget::removeBluetoothStatus(QString arg)
{
    if (m_devAddress.contains(arg)) {
        qDebug()<<"移除信号可用 " << arg;
        handBlueToothData();
        initBluetoothStatus();
    }

}


void ModifybluetoothWidget::mouseReleaseEvent(QMouseEvent *event)
{
    if (!m_constatus) {
        return;
    }

    m_pServiceInterface->call("showTrayWidgetUI");
    QWidget::mouseReleaseEvent(event);
}

void ModifybluetoothWidget::paintEvent(QPaintEvent *event)
{
    QStyleOption opt;
    opt.init(this);
    QPainter p(this);
    p.setBrush(qApp->palette().color(QPalette::Button));
    p.setOpacity(0.3);
    p.setPen(Qt::NoPen);
    p.setRenderHint(QPainter::Antialiasing);  // 反锯齿;
    p.drawRoundedRect(opt.rect,28,28);
    style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
    QWidget::paintEvent(event);

}

void ModifybluetoothWidget::setButtonclickSlots()
{
    if (!m_constatus) {
        return;
    }

    m_pServiceInterface->call("showTrayWidgetUI");
    return;
}

void ModifybluetoothWidget::bluetoothservice(bool status)
{
    m_bbluetooththread->quit();
    delete m_bbluetooththread;
    if (status) {
        initBluetoothDbus();
        initBluetoothStatus();
    }
    m_constatus = status;
}

void ModifybluetoothWidget::setLabelText(QString s)
{
    QFontMetrics fontmetrics(m_pbluetoothNameLabel->font());
    QString format = s;
    format=fontmetrics.elidedText(format,Qt::ElideRight,m_pbluetoothNameLabel->width(),Qt::TextShowMnemonic);
    m_pbluetoothNameLabel->setText(format);
//    m_pbluetoothNameLabel->setToolTip(s);
    m_pbluetoothNameLabel->repaint();
}

void bluetooththread::run()
{
    QTime dieTime = QTime::currentTime().addMSecs(2000);
    while( QTime::currentTime() < dieTime )
    QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
    QDBusInterface *m_pServiceInterface = new QDBusInterface(KYLIN_BLUETOOTH_SERVER_NAME,
                                             KYLIN_BLUETOOTH_SERVER_PATH,
                                             KYLIN_BLUETOOTH_SERVER_INTERFACE,
                                             QDBusConnection::sessionBus());
    if (!m_pServiceInterface->isValid()) {
        qDebug()<<"false";
        delete m_pServiceInterface;
        emit result(false);
    }else {
        qDebug()<<"successed";
        delete m_pServiceInterface;
        emit result(true);
    }
}

BlueToolsLabel::BlueToolsLabel(QWidget *parent) : QLabel(parent)
{
    this->setFixedSize(30, 20);
    QPixmap myPix(KYLIN_WIFI_PRESS_PATH);
    this->setPixmap(myPix);
}

void BlueToolsLabel::mouseReleaseEvent(QMouseEvent *ev)
{
    Q_UNUSED(ev);
    emit LabelClicked();
}
