#include "qdevitem.h"

QDevItem::QDevItem(QString address, QStringList deviceinfo, bool connected, QWidget *parent):
    QFrame(parent),
    _Address(address),
    _Connected(connected),
    _Name(deviceinfo.at(0)),
    _Battery(deviceinfo.at(2)),
    _MType(deviceinfo.at(1))
{
    initMap();
    qDebug() << " get dev Battery : " << deviceinfo.at(0) << _Battery;

    if(QGSettings::isSchemaInstalled("org.ukui.style")) {
        StyleSettings = new QGSettings("org.ukui.style");
        connect(StyleSettings,&QGSettings::changed,this,[=]{
            this->update();
        });
    }
    const QByteArray transparency_id(TRANSPARENCY_SETTINGS);
    if(QGSettings::isSchemaInstalled(transparency_id)){
        transparency_gsettings = new QGSettings(transparency_id);
    }
    if(QGSettings::isSchemaInstalled(transparency_id)){
       tran=transparency_gsettings->get(TRANSPARENCY_KEY).toDouble()*255;
    }

    this->setFixedSize(404,50);
    this->setObjectName(address);
    _MStatus = Status::Nomal;
    _clicked = false;
    _pressFlag = false;

    InitMemberVariables();
}

QDevItem::~QDevItem()
{

}

void QDevItem::initMap() {
    typeMap = new QMap<QString, QIcon>();
    typeMap->insert(QString("phone"), QIcon::fromTheme("phone-symbolic"));
    typeMap->insert(QString("computer"), QIcon::fromTheme("video-display-symbolic"));
    typeMap->insert(QString("headset"), QIcon::fromTheme("audio-headset-symbolic"));
    typeMap->insert(QString("headphones"), QIcon::fromTheme("audio-headphones-symbolic"));
    typeMap->insert(QString("audiovideo"), QIcon::fromTheme("audio-speakers-symbolic"));
    typeMap->insert(QString("keyboard"), QIcon::fromTheme("input-keyboard-symbolic"));
    typeMap->insert(QString("mouse"), QIcon::fromTheme("input-mouse-symbolic"));
}

void QDevItem::SendMessage(bool connected)
{
    QString text;
    if (connected) {
        text = QString(tr("The connection with the Bluetooth device “%1” is successful!").arg(_Name));

    } else {
        text = QString(tr("Bluetooth device “%1” disconnected!").arg(_Name));
    }
    Config::SendNotifyMessage(text);
}

void QDevItem::connectedChangedSlot(bool connected) {
    qDebug() << Q_FUNC_INFO << connected;
    if (_clicked) {
        _iconTimer->stop();
        _clicked = false;
    }
    if (_Connected == connected)
        return;
    _Connected = connected;
    qDebug() << Q_FUNC_INFO << __LINE__;
    update();
    SendMessage(connected);
}

void QDevItem::InitMemberVariables()
{
    _iconTimer = new QTimer(this);

    connect(_iconTimer,&QTimer::timeout,this,[=]{
        if (iconFlag == 0)
            iconFlag = 7;
        iconFlag--;
        update();
    });
}

void QDevItem::setFocusStyle(bool val) {
    _focused = val;
    if (val)
        _MStatus = Status::Hover;
    else
        _MStatus = Status::Nomal;
    this->update();
}

void QDevItem::pressEnterCallback() {
    _MStatus = Status::Click;
    this->update();
    MouseClickedFunc();
    _MStatus = Status::Hover;
    this->update();
}

void QDevItem::enterEvent(QEvent *event)
{
    Q_UNUSED(event);
    if (_focused)
        return;
    _leaved = false;
    _MStatus = Status::Hover;
    update();
}

void QDevItem::leaveEvent(QEvent *event)
{
    Q_UNUSED(event);
    if (_focused)
        return;
    _leaved = true;
    _MStatus = Status::Nomal;
    update();
}

void QDevItem::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton && !_clicked) {
        _pressFlag = true;
        _MStatus = Status::Click;
        this->update();
    }
}

void QDevItem::mouseReleaseEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton && _pressFlag) {
        if (_leaved)
            _MStatus = Status::Nomal;
        else
            _MStatus = Status::Hover;
        MouseClickedFunc();
    }
}

void QDevItem::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);

    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);
    painter.setPen(QColor(Qt::transparent));

    DrawBackground(painter);
    DrawStatusIcon(painter);
    DrawText(painter);
    DrawBattery(painter);

    if (!_focused)
        return;
    QPainter pt(this);
    QColor color = QColor("#818181");
    pt.setPen(color);
    QRect rect = this->rect();
    rect.setWidth(this->rect().width());
    rect.setHeight(this->rect().height());
    pt.setRenderHint(QPainter::Antialiasing);
    pt.drawRoundedRect(rect,8,8,Qt::AbsoluteSize);
}

/************************************************
 * @brief  根据设备状态返回自定义控件的背景色
 * @param  null
 * @return 返回类型为QColor
*************************************************/
QColor QDevItem::getPainterBrushColor()
{
    QColor color;
    switch (_MStatus) {
    case Status::Nomal:
        if(StyleSettings->get("style-name").toString() == "ukui-light" || StyleSettings->get("style-name").toString() == "ukui-default")
            color = QColor(255,255,255,0);
        else {
            color = QColor(QPalette::Base);
            color.setAlpha(0);
        }
        break;
    case Status::Hover:
        if(StyleSettings->get("style-name").toString() != "ukui-dark")
            color = QColor(217,217,217,tran);
        else
            color = QColor(55, 55, 59, tran);
        break;
    case Status::Click:
        if(StyleSettings->get("style-name").toString() != "ukui-dark")
            color = QColor(209, 209, 209,tran);
        else
            color = QColor(102, 102, 102, tran);
        break;
    default:
        if(StyleSettings->get("style-name").toString() != "ukui-dark")
            color = QColor(223,223,223,tran);
        else{
            color = QColor(QPalette::Base);
            color.setAlpha(0);
        }
        break;
    }

    return color;
}

/************************************************
 * @brief  根据设备状态返回自定义控件的设备状态的颜色
 * @param  null
 * @return 返回类型为QColor
*************************************************/
QColor QDevItem::getDevStatusColor()
{
    QColor color;
    if (_Connected) {
        if (_MStatus == Status::Click)
            color = QColor("#1699CF");
        else
            color = QColor("#2FB3E8");
    } else {
        if(StyleSettings->get("style-name").toString() != "ukui-dark") {
            if (_MStatus == Status::Click)
                color = QColor("#E0E0E0");
            else
                color = QColor("#DFDFDF");
        } else {
            if (_MStatus == Status::Click)
                color = QColor("#444444");
            else
                color = QColor("#666666");
        }
        color.setAlpha(tran);
    }

    return color;
}

/************************************************
 * @brief  根据设备类型返回对应的主题图标
 * @param  null
 * @return 返回类型为QPixmap的图标
*************************************************/
QPixmap QDevItem::getDevTypeIcon()
{
    QIcon icon;
    if (_clicked) {
        icon = QIcon::fromTheme("ukui-loading-" + QString::number(iconFlag) + "-symbolic");
    } else {
        if (typeMap->keys().contains(_MType))
            icon = typeMap->value(_MType);
        else
            icon = QIcon::fromTheme("bluetooth-symbolic");
    }
    return icon.pixmap(18,18);
}

/************************************************
 * @brief  绘制自定义控件的背景色
 * @param  painter
 * @return null
*************************************************/
void QDevItem::DrawBackground(QPainter &painter)
{
    painter.save();
    painter.setBrush(getPainterBrushColor());
    painter.drawRoundedRect(this->rect(),8,8,Qt::AbsoluteSize);
    painter.restore();
}

/************************************************
 * @brief  绘制自定义控件的设备状态图标
 * @param  painter
 * @return null
*************************************************/
void QDevItem::DrawStatusIcon(QPainter &painter)
{
    QPixmap devpixmap;

    painter.save();
    painter.setBrush(getDevStatusColor());
    painter.drawEllipse(16,7,36,36);
    painter.setRenderHint(QPainter::SmoothPixmapTransform);

    if(StyleSettings->get("style-name").toString() != "ukui-dark") {
        painter.setPen(QColor(Qt::black));
        if (_Connected)
            devpixmap = Config::loadSvg(getDevTypeIcon(), Config::PixmapColor::WHITE);
        else
            devpixmap = getDevTypeIcon();
    } else {
        if (StyleSettings->get("icon-theme-name").toString() == "ukui-icon-theme-classical")
            devpixmap = getDevTypeIcon();
        else {
            painter.setPen(QColor(Qt::white));
            devpixmap = Config::loadSvg(getDevTypeIcon(), Config::PixmapColor::WHITE);
        }
    }

    style()->drawItemPixmap(&painter, QRect(25, 16, 18, 18), Qt::AlignCenter, devpixmap);
    painter.restore();
}

/************************************************
 * @brief  绘制自定义控件的文字
 * @param  painter
 * @return null
*************************************************/
void QDevItem::DrawText(QPainter &painter)
{
    painter.save();
    if(StyleSettings->get("style-name").toString() != "ukui-dark")
        painter.setPen(QColor(Qt::black));
    else
        painter.setPen(QColor(Qt::white));

    QString nName;
    double fontSize = StyleSettings->get("system-font-size").toDouble() - 11;
    QFont ft;
    ft.setPixelSize(18 + fontSize);
    QFontMetrics fontMetrics(ft);
    nName = fontMetrics.elidedText(_Name, Qt::ElideRight, 280);
    if (_Name.size() != nName.size())
        this->setToolTip(_Name);

    if (fontSize >= 14)
        painter.drawText(62,8,280,30,Qt::AlignLeft|Qt::AlignVCenter, nName);
    else
        painter.drawText(62,12,280,28,Qt::AlignLeft|Qt::AlignVCenter, nName);

    painter.restore();
}

/************************************************
 * @brief  绘制电池
 * @param  painter
 * @return null
*************************************************/
void QDevItem::DrawBattery(QPainter &painter)
{
    int battery = _Battery.toInt();
    if (battery == -1 || !_Connected)
        return;

    painter.save();
    QString batteryIcon = QString("battery-level-") + QString::number(battery / 10 * 10) + QString("-symbolic");
    QString batteryString = _Battery + QString("%");
    QPixmap batteryPixmap;

    if(StyleSettings->get("style-name").toString() != "ukui-dark") {
        painter.setPen(QColor(Qt::black));
        batteryPixmap = Config::loadSvg(QIcon::fromTheme(batteryIcon).pixmap(20,20), Config::PixmapColor::BLACK);
    } else {
        painter.setPen(QColor(Qt::white));
        batteryPixmap = Config::loadSvg(QIcon::fromTheme(batteryIcon).pixmap(20,20), Config::PixmapColor::WHITE);
    }

    if (StyleSettings->get("system-font-size").toDouble() >= 14)
        painter.drawText(344,8,52,28,Qt::AlignVCenter | Qt::AlignLeft, batteryString);
    else
        painter.drawText(344,12,52,28,Qt::AlignLeft, batteryString);
    style()->drawItemPixmap(&painter, QRect(320, 14, 20, 20), Qt::AlignVCenter | Qt::AlignLeft, batteryPixmap);
    painter.restore();
}

/************************************************
 * @brief  当鼠标在该自定义控件点击时，执行该函数
 * @param  null
 * @return null
*************************************************/
void QDevItem::MouseClickedFunc()
{
    emit devConnect(!_Connected);
    startIconTimer();
}

void QDevItem::startIconTimer() {
    _clicked = true;
    _pressFlag = false;
    //设置_iconTimer定时器开始，来实现loading效果
    if (!_iconTimer->isActive()) {
        _iconTimer->start(110);

        //以下这个只执行一次的定时器，用来设置点击后加载动画的持续时间
        QTimer::singleShot(7000,this,[=]{
            if (_clicked) {
                _iconTimer->stop();
                _clicked = false;
                update();
            }
        });
    }
}

bool QDevItem::isConnected() {
    return _Connected;
}
