#include "pincodewidget.h"
#include "config/xatom-helper.h"
#include "config/config.h"

PinCodeWidget::PinCodeWidget(QString name, QString pin, bool flag)
   : dev_name(name),
     PINCode(pin),
     show_flag(flag)
{
    if (envPC == Environment::LAIKA || envPC == Environment::MAVIS)
        is_Intel = true;
    else
        is_Intel = false;

    if (envPC == Environment::HUAWEI)
        scale = QGSettings("org.ukui.SettingsDaemon.plugins.xsettings").get("scaling-factor").toDouble();

    if(QGSettings::isSchemaInstalled("org.ukui.style")){
        settings = new QGSettings("org.ukui.style");
        connect(settings,&QGSettings::changed,this,&PinCodeWidget::GSettingsChanges);
    }

    //窗管协议
    MotifWmHints hints;
    hints.flags = MWM_HINTS_FUNCTIONS|MWM_HINTS_DECORATIONS;
    if (is_Intel)
        hints.functions = MWM_FUNC_CLOSE;
    else
        hints.functions = MWM_FUNC_ALL;
    hints.decorations = MWM_DECOR_BORDER;
    XAtomHelper::getInstance()->setWindowMotifHint(this->winId(), hints);

    QPalette palette;
    if(settings->get("style-name").toString() == "ukui-default" || settings->get("style-name").toString() == "ukui-light"){
        palette.setColor(QPalette::Background,QColor(255,255,255));
    }else{
        palette.setColor(QPalette::Background,QColor(0,0,0));
    }
    this->setWindowIcon(QIcon::fromTheme("bluetooth"));
    if (is_Intel)
        this->setWindowTitle(tr("Bluetooth Connection"));
    else
        this->setWindowTitle(tr("Bluetooth pairing"));
    this->setAttribute(Qt::WA_DeleteOnClose);

    this->setPalette(palette);
    this->setAutoFillBackground(true);

    QFont ft_14, ft_16, ft_20, ft_24, ft_40;
    double ft_size = settings->get("system-font-size").toDouble() - 11;
    ft_14.setPixelSize((14 + ft_size) * scale);
    ft_16.setPixelSize((16 + ft_size) * scale);
    ft_20.setPixelSize((20 + ft_size) * scale);
    ft_24.setPixelSize((24 + ft_size) * scale);
    ft_40.setPixelSize((40 + ft_size) * scale);
    tip_label = new QLabel(this);
    tip_label->setFont(ft_14);
    tip_label->setWordWrap(true);
    tip_label->setToolTip(dev_name);

    PIN_label = new QLabel(this);
    PIN_label->setFont(ft_24);

    accept_btn = new QPushButton(tr("Connect"),this);

    refuse_btn = new QPushButton(tr("Refuse"),this);

    if(show_flag){
        connect(accept_btn,&QPushButton::clicked,this,&PinCodeWidget::onClick_accept_btn);
        connect(refuse_btn,&QPushButton::clicked,this,&PinCodeWidget::onClick_refuse_btn);
    }else{
        connect(accept_btn,&QPushButton::clicked,this,&PinCodeWidget::onClick_close_btn);
        accept_btn->setText(tr("Confirm"));
        accept_btn->adjustSize();
        //accept_btn->setddVisible(false);
        refuse_btn->setVisible(false);
    }

    if (is_Intel) {
        this->setWindowFlags(Qt::Dialog);
        this->setFixedSize(510, 239);
        tip_label->setFont(ft_16);
        PIN_label->setFont(ft_40);
        tip_label->setGeometry(24,24,450,50);
        PIN_label->setGeometry(24,88,462,47);
        accept_btn->setGeometry(374,159,112,56);
        refuse_btn->setGeometry(246,159,112,56);
    } else {
        this->setFixedSize(520 * scale ,212 * scale);
        title_icon = new QLabel(this);
        title_icon->setPixmap(QIcon::fromTheme("preferences-system-bluetooth").pixmap(22 * scale,22 * scale));
        title_icon->resize(22 * scale,22 * scale);

        title_text = new QLabel(tr("Bluetooth Connections"),this);
        title_text->setFont(ft_14);
        title_text->adjustSize();

        close_btn = new QPushButton(this);
        QIcon icon = QIcon::fromTheme("window-close-symbolic");
        close_btn->setIcon(icon);
        close_btn->setProperty("isWindowButton", 0x2);
        close_btn->setProperty("useIconHighlightEffect", 0x8);
    //    close_btn->setProperty("setIconHighlightEffectDefaultColor", QColor(Qt::white));
        close_btn->setFlat(true);
        connect(close_btn,&QPushButton::clicked,this,&PinCodeWidget::onClick_close_btn);

        close_btn->setGeometry(480 * scale,8 * scale,30 * scale,30 * scale);
        title_icon->setGeometry(8 * scale, 8 * scale, 22 * scale, 22 * scale);
        title_text->setGeometry(38 * scale, 9 * scale, 160 * scale, 20 * scale);
        PIN_label->setGeometry(25 * scale,98 * scale,207 * scale,36 * scale);
        tip_label->setGeometry(25 * scale,56 * scale,437 * scale,48 * scale);
        accept_btn->setGeometry(388 * scale,152 * scale,108 * scale,36 * scale);
        refuse_btn->setGeometry(264 * scale,152 * scale,108 * scale,36 * scale);
    }
    updateUIInfo(name, pin);
    QList<QScreen *> list = QGuiApplication::screens();
    this->move(list.at(0)->size().width()/2-this->width()/2,list.at(0)->size().height()/2-this->height()/2);
}

PinCodeWidget::~PinCodeWidget()
{
    qDebug() << Q_FUNC_INFO << __LINE__ << dev_name << PINCode << show_flag;
}

void PinCodeWidget::pairFailureShow()
{
    qDebug() << Q_FUNC_INFO << __LINE__;
    if (is_Intel) {
        warn_icon = new QLabel(this);
        warn_icon->setFixedSize(64 * scale,64 * scale);
        qDebug() << Q_FUNC_INFO << __LINE__;
        warn_icon->setPixmap(QPixmap("/usr/share/ukui-bluetooth/connection-failed.svg"));
        warn_icon->setGeometry(223 * scale,42 * scale,64 * scale,64 * scale);
        warn_icon->setVisible(true);
        tip_label->setText(QString(tr("Bluetooth Connect Failed")));
        tip_label->setGeometry(210 * scale,108 * scale,190 * scale,28 * scale);
        tip_label->setStyleSheet("QLabel{\
                                         font-family: NotoSansCJKsc;\
                                         font-size: 16px;\
                                         line-height: 19px;\
                                         text-align: center;\
                                         color: #FB5050;}");
        PIN_label->setVisible(false);
        accept_btn->setVisible(false);
        refuse_btn->setText(tr("Close"));
        refuse_btn->setGeometry(374 * scale,159 * scale,112 * scale,56 * scale);
        return;
    }
    QMessageBox msgBox;
    msgBox.setParent(this);
    msgBox.setIcon(QMessageBox::Warning);
    msgBox.setWindowTitle(tr("Pair"));
    msgBox.setText(tr("Connect Failed!"));
    msgBox.show();
    Config::setKdkGeometry(msgBox.windowHandle(),
                           msgBox.width(),
                           msgBox.height(),
                           true);
    int ret = msgBox.exec();
    if(ret){
        qDebug() << Q_FUNC_INFO << this << __LINE__;
        this->setHidden(true);
        emit msgShowedOver();
    }
}

void PinCodeWidget::updateUIInfo(const QString &name, const QString &pin)
{
    qDebug() << Q_FUNC_INFO  << this->isActiveWindow() << __LINE__;
    PINCode = pin;
    PIN_label->setText(pin);
    PIN_label->update();
    QFontMetrics fontMetrics(tip_label->font());
    QString Name = fontMetrics.elidedText(name, Qt::ElideRight, 240);
    QString tip_text;
    if(show_flag)
        if (is_Intel)
            tip_text = tr("If the PIN on \'")+Name+tr("\' is the same as this PIN. Please press \'Connect\'");
        else
            tip_text = tr("If \'")+Name+tr("\' the PIN on is the same as this PIN. Please press \'Connect\'.");
    else
        tip_text = QString(tr("Please enter the following PIN code on the bluetooth device '%1' and press enter to pair:")).arg(Name);
//    QString show_text = fontMetrics.elidedText(tip_text, Qt::ElideMiddle, tip_label->width());
    if (Name.length() != name.length())
        tip_label->setToolTip(name);
    tip_label->setText(tip_text);
    tip_label->update();

    if (!this->isActiveWindow())
        this->setHidden(false);
}

void PinCodeWidget::onClick_close_btn(bool)
{
    qDebug() << Q_FUNC_INFO << __LINE__;
    if (show_flag) {
        emit this->rejected();
        this->close();
    } else {
        emit this->msgShowedOver();
    }
}

void PinCodeWidget::onClick_accept_btn(bool)
{
    qDebug() << "pincodewindget.cpp : accpet";
    emit this->accepted();
    this->close();
}

void PinCodeWidget::onClick_refuse_btn(bool)
{
    emit this->rejected();
    this->close();
}

void PinCodeWidget::GSettingsChanges(const QString &key)
{
    QPalette palette;
    qDebug() << Q_FUNC_INFO << key;
    if(key == "styleName"){
        if(settings->get("style-name").toString() == "ukui-default" || settings->get("style-name").toString() == "ukui-light"){
            palette.setColor(QPalette::Background,QColor(Qt::white));
        }else{
            palette.setColor(QPalette::Background,QColor(Qt::black));
        }
    }
    if (key == "systemFontSize") {
        double size = settings->get("system-font-size").toDouble() - 11;
        qDebug() << Q_FUNC_INFO << size;
        QFont ft, ft1;
        ft.setPixelSize((14 + size) * scale);
        tip_label->setFont(ft);
        title_text->setFont(ft);
        ft1.setPixelSize((24 + size) * scale);
        PIN_label->setFont(ft1);
    }
    this->setPalette(palette);
    this->update();
}

QPushButton* PinCodeWidget::getButton() {
    switch (pressCnt) {
    case 1:
        if (!accept_btn->isVisible() || !refuse_btn->isVisible())
            ++pressCnt;
        if(accept_btn->isVisible())
            return accept_btn;
        else if (refuse_btn->isVisible()){
            return refuse_btn;
        }
        return nullptr;
    case 2:
        return refuse_btn;
    case 3:
        return close_btn;
    default:
        return nullptr;
    }
}

void PinCodeWidget::paintEvent(QPaintEvent *event) {
    QPainter pt(this);
    QColor color = QColor("#818181");
    pt.setPen(color);
    selectedBtn = getButton();
    if (selectedBtn == nullptr)
        return;
    QRect rect = selectedBtn->geometry();
    pt.setRenderHint(QPainter::Antialiasing);
    pt.drawRect(rect);
}

void PinCodeWidget::keyPressEvent(QKeyEvent *event) {
    switch (event->key()) {
    case Qt::Key_Tab:
        qDebug() << "press Tab";
        ++pressCnt;
        if (pressCnt == 4)
            pressCnt = 1;
        this->update();
        break;
    case Qt::Key_Enter:
    case Qt::Key_Return:
        qDebug() << "press Enter";
        if (selectedBtn == nullptr)
            return;
        selectedBtn->clicked();
        break;
    case Qt::Key_Escape:
        qDebug() << "press Esc";
        if (pressCnt == 0)
            this->close();
        pressCnt = 0;
        this->update();
        break;
    default:
        break;
    }
}
