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

bool BluetoothFileTransferWidget::isShow = false;
BluetoothFileTransferWidget::BluetoothFileTransferWidget(QStringList files, QMap<QString, QStringList> devicelist, QString dev_address):
//    QWidget(parent),
    selectedFiles(files)
{
    fileNums = selectedFiles.size();
    isShow = true;
    send_state = _SEND_NONE;

    if (envPC == Environment::LAIKA || envPC == Environment::MAVIS)
        is_Intel = true;
    else
        is_Intel = false;

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

    //窗管协议
//    setAttribute(Qt::WA_TranslucentBackground);
//    setProperty("useSystemStyleBlur", true);
    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);

    qDebug() << Q_FUNC_INFO << __LINE__;
    this->setWindowIcon(QIcon::fromTheme("bluetooth"));
    this->setWindowTitle(tr("Bluetooth file transfer"));
    this->setAttribute(Qt::WA_DeleteOnClose);
    const QByteArray transparency_id("org.ukui.control-center.personalise");
    if(QGSettings::isSchemaInstalled(transparency_id)){
        transparency_gsettings = new QGSettings(transparency_id);
    }
    if(QGSettings::isSchemaInstalled(transparency_id)){
       tran=transparency_gsettings->get("transparency").toDouble()*255;
       connect(transparency_gsettings, &QGSettings::changed, this, [=] {
           tran=transparency_gsettings->get("transparency").toDouble()*255;
           this->update();
       });
    }
    QPalette palette;
    if(GSettings->get("style-name").toString() != "ukui-dark"){
        palette.setColor(QPalette::Background,QColor(255,255,255));
    }else{
        palette.setColor(QPalette::Background,QColor(0,0,0));
    }
    this->setPalette(palette);
    this->setAutoFillBackground(true);

    QDesktopWidget *deskdop = QApplication::desktop();
    move((deskdop->width()-this->width())/2, (deskdop->height()-this->height())/2);

    tip_text = new QLabel(this);

    tip_text->setWordWrap(true);
    tip_text->setVisible(false);

    initFileInfo();

    target_icon = new QLabel(this);
    target_icon->setPixmap(file_icon.at(0).pixmap(64,64));

    int ii = file_size.at(0).indexOf('i');
    QString _tmp_size = file_size.at(0);
    if (ii != -1)
        _tmp_size.remove(ii, 1);
    QStringList strSlipList = _tmp_size.split(" ");
    qDebug() << _tmp_size << strSlipList;
    bool isBytes = false;
    if (strSlipList.at(strSlipList.size() - 1) == "字节") {
        _tmp_size.remove("字节");
        isBytes = true;
    }
    if (strSlipList.at(strSlipList.size() - 1) == "bytes") {
        _tmp_size.remove("bytes");
        isBytes = true;
    }
    if(isBytes)
        _tmp_size.append(tr("Bytes"));

    target_size = new QLabel(_tmp_size,this);

    QFontMetrics fontMetrics(target_size->font());
    QString fileName;
    QString Name = selectedFiles.at(0).split("/").at(selectedFiles.at(0).split("/").length()-1);
    if (fileNums > 1) {
        fileName = fontMetrics.elidedText("\""
                                          + Name
                                          +"\"", Qt::ElideMiddle, 280);
        fileName.append(tr(" and ")+QString::number(fileNums)+tr(" files more"));
    }else
        fileName = fontMetrics.elidedText(Name, Qt::ElideMiddle, 280);
    target_name = new QLabel(fileName,this);
    target_name->setToolTip(Name);


    transNum = new QLabel("1/"+QString::number(fileNums), this);
    transNum->setVisible(false);

    m_progressbar = new QProgressBar(this);
    m_progressbar->setOrientation(Qt::Horizontal);
    m_progressbar->setTextVisible(false);
    m_progressbar->setVisible(false);

    Tiptop = new QLabel(tr("Select Device"),this);
    Tiptop->setFixedSize(100,20);

    ok_btn = new QPushButton(tr("OK"),this);
    ok_btn->setFixedSize(100,36);
    if(selectedDev == nullptr) {
        ok_btn->setEnabled(false);
    }
    connect(ok_btn,&QPushButton::clicked,this,&BluetoothFileTransferWidget::onClicked_OK_Btn);

    cancel_btn = new QPushButton(tr("Cancel"),this);
    cancel_btn->setFixedSize(100,36);
    connect(cancel_btn,&QPushButton::clicked,this,[=]{
        this->close();
        if (this->send_state != _SEND_COMPLETE || this->send_state != _SEND_FAILURE)
            this->close_the_pre_session();
    });

    qtw = new QTreeWidget(this);
    qtw->setFixedSize(456,356);
    qtw->setHeaderHidden(true);
    qtw->addTopLevelItems(toolbutton_list);
    qtw->setAlternatingRowColors(true);
    connect(qtw, &QTreeWidget::itemPressed, this, [=](QTreeWidgetItem *item, int column){
        Q_UNUSED(column)
        if(selectedDev != nullptr)
            if (GSettings->get("style-name").toString() != "ukui-dark")
                selectedDev->setIcon(0, QIcon(Config::loadSvg(selectedDev->icon(0).pixmap(64,64), Config::PixmapColor::BLACK)));
            else
                selectedDev->setIcon(0, QIcon(Config::loadSvg(selectedDev->icon(0).pixmap(64,64), Config::PixmapColor::WHITE)));
        selectedDev = item;
        selectedDev->setIcon(0, QIcon(Config::loadSvg(selectedDev->icon(0).pixmap(64,64), Config::PixmapColor::WHITE)));
        if (!ok_btn->isEnabled())
            ok_btn->setEnabled(true);
    });
    initQTreeWidget(devicelist,dev_address);

    tranfer_status_icon = new QLabel(this);
    tranfer_status_icon->setPixmap(QIcon::fromTheme("kylin-dialog-warning").pixmap(22,22));
    if (tranfer_status_icon->pixmap()->isNull())
        tranfer_status_icon->setPixmap(QIcon::fromTheme("dialog-warning").pixmap(22,22));
    tranfer_status_icon->setFixedSize(22,22);
    tranfer_status_icon->setVisible(false);

    tranfer_status_text = new QLabel(this);
    tranfer_status_text->setText(tr("File Transmission Failed !"));
    tranfer_status_text->setVisible(false);

    if (is_Intel)
        initIntelLayout();
    else
        initLayout();

    init_m_progressbar_value(_filesize.at(0));
    this->setFocus();
}

BluetoothFileTransferWidget::~BluetoothFileTransferWidget()
{
    isShow = false;
}

void BluetoothFileTransferWidget::initQTreeWidget(QMap<QString, QStringList> devicelist, QString dev_address)
{
    for(int i=0; i < devicelist.values().size(); i++){
//        qDebug() << Q_FUNC_INFO << device_list.at(i)->type() << device_list.at(i)->name();
        BluezQt::Device::Type type = BluezQt::Device::stringToType(devicelist.values().at(i).at(1));
        if((type == BluezQt::Device::Phone)||(type == BluezQt::Device::Computer)){
                QIcon icon;
                switch (type){
                case BluezQt::Device::Type::Phone:
                    icon = QIcon::fromTheme("phone-apple-iphone-symbolic");
                    break;
                case BluezQt::Device::Type::Computer:
                    icon = QIcon::fromTheme("video-display-symbolic");
                    break;
                case BluezQt::Device::Type::Uncategorized:
                default:
                    icon = QIcon::fromTheme("bluetooth-symbolic");
                    break;
                }

                QTreeWidgetItem *item = new QTreeWidgetItem(qtw);
                item->setExpanded(true);
                item->setSizeHint(0,QSize(456, 50));
                item->setText(0, devicelist.values().at(i).at(0));
                item->setToolTip(0, devicelist.values().at(i).at(0));
                if (GSettings->get("style-name").toString() != "ukui-dark")
                    item->setIcon(0,QIcon(icon.pixmap(64,64)));
                else
                    item->setIcon(0, QIcon(Config::loadSvg(icon.pixmap(64,64), Config::PixmapColor::WHITE)));
                itemMap.insert(item, devicelist.key(devicelist.values().at(i)));
                toolbutton_list.append(item);
                if (dev_address == devicelist.key(devicelist.values().at(i))) {
                    item->setSelected(true);
                    item->setIcon(0, QIcon(Config::loadSvg(icon.pixmap(64,64), Config::PixmapColor::WHITE)));
                    selectedDev = item;
                    if (!ok_btn->isEnabled())
                        ok_btn->setEnabled(true);
                }
        }
    }
}


void BluetoothFileTransferWidget::initLayout() {
    this->setFixedSize(520,620);
    title_icon = new QLabel(this);
    title_icon->setPixmap(QIcon::fromTheme("preferences-system-bluetooth").pixmap(22,22));
    title_icon->resize(22,22);

    title_text = new QLabel(tr("Bluetooth file transfer"),this);

    close_btn = new QPushButton(this);
    close_btn->setIcon(QIcon::fromTheme("window-close-symbolic"));
    close_btn->setProperty("isWindowButton", 0x2);
    close_btn->setProperty("useIconHighlightEffect", 0x8);
    close_btn->setFlat(true);
    close_btn->setFixedSize(30,30);
    connect(close_btn,&QPushButton::clicked,this,[=]{
        this->close();
        if (this->send_state != _SEND_COMPLETE || this->send_state != _SEND_FAILURE)
            this->close_the_pre_session();
    });

    //布局
    qtw->resize(456,356);
    title_icon->setGeometry(8,8,22,22);
    title_text->setGeometry(36,8,200,20);
    close_btn->setGeometry(484,4,30,30);
    tranfer_status_text->setGeometry(62,53,376,27);
    tranfer_status_icon->setGeometry(32,55,22,22);
    cancel_btn->setGeometry(280,560,100,36);
    ok_btn->setGeometry(390,560,100,36);
    qtw->setGeometry(32,175,456,356);
    Tiptop->setGeometry(32,144,100,20);
    target_size->setGeometry(112,88,88,30);
    tip_text->setGeometry(32,52,452,56);
    target_icon->setGeometry(32,56,64,64);
    target_name->setGeometry(112,63,400,30);
    transNum->setGeometry(459,168,52,20);
    if (fileNums > 1)
        m_progressbar->setGeometry(32,175,406,10);
    else
        m_progressbar->setGeometry(32,185,456,10);

    //字体
    double size = GSettings->get("system-font-size").toDouble() - 11;
    QFont ft;
    ft.setPixelSize(14+size);
    title_text->setFont(ft);
    target_size->setFont(ft);
    target_name->setFont(ft);
    transNum->setFont(ft);
    Tiptop->setFont(ft);
    ft.setPixelSize(18+size);
    tip_text->setFont(ft);
    tranfer_status_text->setFont(ft);
}

void BluetoothFileTransferWidget::initIntelLayout() {
    this->setWindowFlags(Qt::Dialog);
    this->setFixedSize(478,530);
    cancel_btn->setFixedSize(112,56);
    ok_btn->setFixedSize(112,56);
    target_name->setFixedHeight(30);
    target_size->setFixedWidth(88);
    qtw->resize(430,296);

    ok_btn->setGeometry(342,450,112,56);
    cancel_btn->setGeometry(214,450,112,56);
    tranfer_status_text->setGeometry(62,33,376,27);
    tranfer_status_icon->setGeometry(32,35,22,22);
    qtw->setGeometry(24,139,430,296);
    Tiptop->setGeometry(32,111,100,20);
    target_size->setGeometry(104,60,88,30);
    tip_text->setGeometry(24,24,430,56);
    target_icon->setGeometry(24,24,64,64);
    target_name->setGeometry(104,28,400,30);
    transNum->setGeometry(410,148,52,20);
    if (fileNums > 1)
        m_progressbar->setGeometry(24,155,372,8);
    else
        m_progressbar->setGeometry(24,155,420,8);

    double size = GSettings->get("system-font-size").toDouble() - 11;
    QFont ft;
    ft.setPixelSize(14+size);
    target_size->setFont(ft);
    target_name->setFont(ft);
    transNum->setFont(ft);
    Tiptop->setFont(ft);
    ft.setPixelSize(18+size);
    tip_text->setFont(ft);
    tranfer_status_text->setFont(ft);
    this->show();
    this->activateWindow();
}

void BluetoothFileTransferWidget::initFileInfo() {
    for (int i = 0; i < fileNums; i++) {
        Get_fie_type(i);
    }
    qDebug() << Q_FUNC_INFO << __LINE__;
}

void BluetoothFileTransferWidget::Get_fie_type(int i)
{
    GError *error;
    qDebug() << Q_FUNC_INFO << selectedFiles.at(i);
    GFile *file = g_file_new_for_path(selectedFiles.at(i).toStdString().c_str());
    GFileInfo *file_info = g_file_query_info(file,"*",G_FILE_QUERY_INFO_NONE,NULL,&error);

    file_size.push_back(g_format_size_full(g_file_info_get_size(file_info),G_FORMAT_SIZE_IEC_UNITS));
    _filesize.push_back(g_file_info_get_size(file_info));
    if (g_file_info_get_size(file_info) == 0) {
        QMessageBox *mbox = new QMessageBox(QMessageBox::Warning,tr("Warning"),tr("The selected file is empty, please select the file again !"),QMessageBox::Ok);
        mbox->show();
        Config::setKdkGeometry(mbox->windowHandle(),
                               mbox->width(),
                               mbox->height(),
                               true);
        mbox->exec();
        this->deleteLater();
    }

    QString str = g_file_info_get_content_type(file_info);
    if (str.isEmpty() && g_file_info_has_attribute(file_info, "standard::fast-content-type"))
            str = g_file_info_get_attribute_string(file_info, "standard::fast-content-type");
    filetype.push_back(str);
    qDebug() << Q_FUNC_INFO << str << __LINE__;

    QIcon fileicon;
    if (str.split("/").at(0) == "image"){
        fileicon = QIcon(selectedFiles.at(i));
    }else if (str.split("/").at(0) == "video")
        fileicon = QIcon::fromTheme("video-x-generic");
    else if (str.split("/").at(0) == "audio" ||
             str.split("/").at(0) == "application" ||
             str.split("/").at(0) == "text" ||
             str.split("/").at(0) == "inode"){
        if (QIcon::hasThemeIcon(str.split("/").join("-"))) {
            fileicon = QIcon::fromTheme(str.split("/").join("-"));
        }
    }
    if (fileicon.isNull() && !str.isEmpty()){
        QString icon = g_content_type_get_generic_icon_name(str.toUtf8().constData());
        fileicon = QIcon::fromTheme(icon);
    }
    if (fileicon.isNull()) {
        fileicon = QIcon::fromTheme("text");
    }
    file_icon.push_back(fileicon);
}

void BluetoothFileTransferWidget::Initialize_and_start_animation()
{
    this->setFixedSize(520,276);

    QString nName;
    nName = selectedDev->text(0);
    double size = GSettings->get("system-font-size").toDouble() - 11;
    QFont ft;
    ft.setPixelSize(18 + size);
    tip_text->setFont(ft);
    QFontMetrics fontMetrics(tip_text->font());
    QString fileSource = QString(tr("Transferring to \"")+nName+"\"");
    tip_text->setText(fontMetrics.elidedText(fileSource, Qt::ElideMiddle, tip_text->width()));
    tip_text->setToolTip(nName);
    tip_text->update();

    ok_btn->setVisible(false);
    cancel_btn->setVisible(true);
    m_progressbar->setVisible(true);
    transNum->setVisible(fileNums - 1);
    Tiptop->setVisible(false);
    qtw->setVisible(false);
    tip_text->setVisible(true);
    if (is_Intel) {
        cancel_btn->setGeometry(342, 200, 112, 56);
        target_icon->setGeometry(24,67,64,64);
        target_name->setGeometry(104,71,400,30);
        target_size->setGeometry(104,103,88,30);
    } else {
        cancel_btn->setGeometry(390, 213, 100, 36);
        target_icon->setGeometry(32,105,64,64);
        target_name->setGeometry(112,112,400,30);
        target_size->setGeometry(112,137,88,30);
    }

    main_animation_group = new QParallelAnimationGroup(this);

    QPropertyAnimation *progress_action = new QPropertyAnimation(m_progressbar,"geometry");
    QRect transfer_progress_rect = m_progressbar->geometry();
    transfer_progress_rect.setWidth(0);
    progress_action->setStartValue(transfer_progress_rect);
    progress_action->setEndValue(m_progressbar->geometry());
    progress_action->setDuration(200);

    main_animation_group->addAnimation(progress_action);
    main_animation_group->start();
    connect(main_animation_group,&QParallelAnimationGroup::finished,this,[=]{
        if (is_Intel)
            this->setFixedSize(478,280);
        else
            this->setFixedSize(520,276);
    });
}

void BluetoothFileTransferWidget::init_m_progressbar_value(quint64 value)
{
#if 0
    qDebug() << Q_FUNC_INFO << value;
    m_progressbar->setMinimum(0);
    m_progressbar->setMaximum(value);
    m_progressbar->setValue(0);
#else
    qDebug() << Q_FUNC_INFO << value;
    m_curr_filesize = value ;
    qDebug() << Q_FUNC_INFO << "m_curr_filesize:" << m_curr_filesize;

    m_progressbar->setMinimum(0);
    m_progressbar->setMaximum(QPROGRESSBAR_MAX_IMUM);
    m_progressbar->setValue(0);
#endif
}

void BluetoothFileTransferWidget::insertNewFileList(QStringList fileList) {
    QList<QIcon>   fileIconList;
    QList<quint64> _fileSizeList;
    QList<QString> fileSizeList;
    QList<QString> filetypeList;
    for (int i = 0; i < fileList.size(); i++) {
        GError *error;
        qDebug() << Q_FUNC_INFO << fileList.at(i);
        GFile *file = g_file_new_for_path(fileList.at(i).toStdString().c_str());
        GFileInfo *file_info = g_file_query_info(file,"*",G_FILE_QUERY_INFO_NONE,NULL,&error);
        qDebug() << Q_FUNC_INFO  << g_file_info_get_size(file_info) << g_file_info_get_content_type(file_info);
        qDebug() << Q_FUNC_INFO << __LINE__;

        fileSizeList.push_back(g_format_size_full(g_file_info_get_size(file_info),G_FORMAT_SIZE_IEC_UNITS));
        _fileSizeList.push_back(g_file_info_get_size(file_info));
        QString str = g_file_info_get_content_type(file_info);
        filetypeList.push_back(str);
        qDebug() << Q_FUNC_INFO << __LINE__;
        QIcon fileicon;
        if (str.split("/").at(0) == "image"){
            fileicon = QIcon(fileList.at(i));
            if (fileicon.isNull()) {
                fileicon = QIcon::fromTheme("text");
            }
        }else if (str.split("/").at(0) == "video")
            fileicon = QIcon::fromTheme("video-x-generic");
        else if (str.split("/").at(0) == "audio" ||
                 str.split("/").at(0) == "application" ||
                 str.split("/").at(0) == "text" ||
                 str.split("/").at(0) == "inode"){
            if (QIcon::hasThemeIcon(str.split("/").join("-"))) {
                fileicon = QIcon::fromTheme(str.split("/").join("-"));
            } else {
                fileicon = QIcon::fromTheme("text");
            }
        }else
            fileicon = QIcon::fromTheme("text");
        qDebug() << Q_FUNC_INFO << __LINE__;
        fileIconList.push_back(fileicon);
    }
    filetype.append(filetypeList);
    file_icon.append(fileIconList);
    file_size.append(fileSizeList);
    _filesize.append(_fileSizeList);
    selectedFiles.append(fileList);
    fileNums += fileList.size();
    QFontMetrics fontMetrics(target_size->font());
    if (selectedFiles.size() == 1)
        target_name->setText(fontMetrics.elidedText(selectedFiles.at(0).split("/").at(selectedFiles.at(0).split("/").length()-1), Qt::ElideMiddle, 280));
    else if(selectedFiles.size() > 1)
    {
        target_name->setText(fontMetrics.elidedText("\""
                                                    +selectedFiles.at(0).split("/").at(selectedFiles.at(0).split("/").length()-1)
                                                    +"\"", Qt::ElideMiddle, 280).append(tr(" and ")+QString::number(fileNums)+tr(" files more")));
    }
    target_name->setToolTip(selectedFiles.at(0).split("/").at(selectedFiles.at(0).split("/").length()-1));
    int transfing = fileNums - selectedFiles.size() + 1;
    transNum->setText(QString::number(transfing)+"/"+QString::number(fileNums));
    if (is_Intel)
        if (fileNums > 1)
            m_progressbar->setGeometry(24,155,372,8);
        else
            m_progressbar->setGeometry(24,155,420,8);
    else
        if (fileNums > 1)
            m_progressbar->setGeometry(32,175,406,15);
        else
            m_progressbar->setGeometry(32,185,454,15);
    transNum->setVisible((fileNums - 1) && (this->send_state == _SENDING));
    this->update();
    this->show();
    this->activateWindow();
}


void BluetoothFileTransferWidget::get_transfer_status(QString status, QString dev, QString path)
{
    if (path != _objectPath && path != QString(""))
        return;
    qDebug() << Q_FUNC_INFO << status << dev << _objectPath;
    if(status == QString("Complete")){
        if (selectedFiles.size() > 1) {
            emit continueSendFiles(selectedFiles.at(1) + QString("  ") + filetype.at(1));
            selectedFiles.pop_front();
            file_size.pop_front();
            file_icon.pop_front();
            _filesize.pop_front();
            QFontMetrics fontMetrics(target_size->font());
            if (selectedFiles.size() == 1)
                target_name->setText(fontMetrics.elidedText(selectedFiles.at(0).split("/").at(selectedFiles.at(0).split("/").length()-1), Qt::ElideMiddle, 280));
            else if(selectedFiles.size() > 1)
            {
                target_name->setText(fontMetrics.elidedText("\""
                                                            +selectedFiles.at(0).split("/").at(selectedFiles.at(0).split("/").length()-1)
                                                            +"\"", Qt::ElideMiddle, 280).append(tr(" and ")+QString::number(fileNums)+tr(" files more")));
            }
            else
            {
                tranfer_error();
                this->show();
                this->activateWindow();
                this->send_state = _SEND_FAILURE ;
            }
            target_name->setToolTip(selectedFiles.at(0).split("/").at(selectedFiles.at(0).split("/").length()-1));
            init_m_progressbar_value(_filesize.at(0));

            int ii = file_size.at(0).indexOf('i');
            QString _tmp_size = file_size.at(0);
            _tmp_size.remove(ii, ii);
            if (_tmp_size.at(_tmp_size.size() - 1) != 'B')
                _tmp_size.append("B");

            target_size->setText(_tmp_size);
            target_icon->setPixmap(file_icon.at(0).pixmap(64,64));
            int transfing = fileNums - selectedFiles.size() + 1;
            transNum->setText(QString::number(transfing)+"/"+QString::number(fileNums));
            this->show();
            this->activateWindow();
            return;
        }
        selectedFiles.clear();
        file_size.clear();
        file_icon.clear();
        if(main_animation_group->state() == QAbstractAnimation::Running){
            connect(main_animation_group,&QParallelAnimationGroup::finished,this,[=]{
                tip_text->setVisible(false);
                m_progressbar->setVisible(false);
                transNum->setVisible(false);
            });
        }
        tip_text->setVisible(false);
        m_progressbar->setVisible(false);
        transNum->setVisible(false);

        if(is_Intel) {
            cancel_btn->setText(tr("OK"));
            tranfer_status_icon->setFixedSize(64,64);
            tranfer_status_icon->setPixmap(QPixmap("/usr/share/ukui-bluetooth/file-transfer-success.svg"));
            tranfer_status_text->setText(tr("File Transmition Succeed!"));
            tranfer_status_text->setFixedWidth(500);
            QFont ft;
            ft.setPixelSize(16);
            tranfer_status_text->setFont(ft);
            tranfer_status_icon->setGeometry(207,57,64,64);
            tranfer_status_text->setGeometry(191,129,200,24);
        } else {
            tranfer_status_icon->setPixmap(QIcon::fromTheme("ukui-dialog-success").pixmap(22,22));
            tranfer_status_text->setText(tr("File Transmition Succeed!"));
        }
        tranfer_status_icon->setVisible(true);
        tranfer_status_text->setVisible(true);
        target_icon->setVisible(false);
        target_name->setVisible(false);
        target_size->setVisible(false);

        cancel_btn->setText(tr("Close"));
        emit close_the_pre_session();
        this->show();
        this->activateWindow();
        this->send_state = _SEND_COMPLETE ;
    }else if(status == QString("Active")){
        this->send_state = _SENDING ;
    }else if(status == QString("Error")){
        tranfer_error();
        this->send_state = _SEND_FAILURE ;
        this->show();
        this->activateWindow();
    }
}

void BluetoothFileTransferWidget::tranfer_error()
{
    if (this->send_state == _SEND_FAILURE || send_state == _SEND_COMPLETE)
        return ;
    tip_text->setVisible(false);
    m_progressbar->setVisible(false);
    transNum->setVisible(false);
    target_icon->setVisible(false);
    target_name->setVisible(false);
    target_size->setVisible(false);
    Tiptop->setVisible(false);
    qtw->setVisible(false);

    if (is_Intel){
        tranfer_status_icon->setFixedSize(64,64);
        tranfer_status_icon->setPixmap(QPixmap("/usr/share/ukui-bluetooth/file-transfer-failed.svg"));
        tranfer_status_text->setFixedWidth(500);
        QFont ft;
        ft.setPixelSize(16);
        tranfer_status_text->setFont(ft);
        tranfer_status_icon->setGeometry(207,57,64,64);
        tranfer_status_text->setGeometry(191,129,200,24);
    }

    tranfer_status_icon->setVisible(true);
    tranfer_status_text->setVisible(true);

    cancel_btn->setText(tr("OK"));
    emit close_the_pre_session();
    this->show();
    this->activateWindow();
}

int BluetoothFileTransferWidget::get_send_data_state()
{
    return this->send_state;
}

void BluetoothFileTransferWidget::set_m_progressbar_value(quint64 value, QString path)
{
    if (path != _objectPath)
        return;
    if(--active_flag <= 0)
    {
        int size = (value * QPROGRESSBAR_MAX_IMUM)/m_curr_filesize;
        m_progressbar->setValue(size);
    }
    m_progressbar->repaint();
}

void BluetoothFileTransferWidget::GSettingsChanges(const QString &key)
{
    qDebug() << Q_FUNC_INFO << key;
    if(key == "styleName"){
        QPalette palette;
        if(GSettings->get("style-name").toString() == "ukui-default" || GSettings->get("style-name").toString() == "ukui-light"){
            palette.setColor(QPalette::Background,QColor(255,255,255));
            target_icon->setProperty("setIconHighlightEffectDefaultColor", QColor(0,0,0));
            target_icon->setProperty("useIconHighlightEffect", 0x10);
        }else{
            palette.setColor(QPalette::Background,QColor(0,0,0));
            target_icon->setProperty("setIconHighlightEffectDefaultColor", QColor(255,255,255));
            target_icon->setProperty("useIconHighlightEffect", 0x10);
        }
        this->setPalette(palette);
        this->update();
    }
    if (key == "systemFontSize") {
        double size = GSettings->get("system-font-size").toDouble() - 11;
        QFont ft;
        ft.setPixelSize(14+size);
        title_text->setFont(ft);
        target_size->setFont(ft);
        target_name->setFont(ft);
        transNum->setFont(ft);
        Tiptop->setFont(ft);
        ft.setPixelSize(18+size);
        tip_text->setFont(ft);
        tranfer_status_text->setFont(ft);

        if (selectedDev == nullptr)
            return;
        QFontMetrics fontMetrics(tip_text->font());
        QString fileSource = QString(tr("Transferring to \"")+selectedDev->text(0)+"\"");
        tip_text->setText(fontMetrics.elidedText(fileSource, Qt::ElideMiddle, tip_text->width()));
        tip_text->setToolTip(selectedDev->text(0));
    }
}

void BluetoothFileTransferWidget::onClicked_OK_Btn()
{

    QString dev_addr = itemMap.value(selectedDev);
    qDebug() << Q_FUNC_INFO << dev_addr;
    Initialize_and_start_animation();
    emit this->sender_dev_name(dev_addr, filetype.at(0));
    send_state = _SEND_ACTIVE;
}

void BluetoothFileTransferWidget::initTransferPath(QString path, bool isSend) {
    if(!isSend)
        return;
    _objectPath = path;
    qDebug() << Q_FUNC_INFO << _objectPath;
}

QRect BluetoothFileTransferWidget::getButton() {
    if (pressTabCnt <= 0)
        return QRect();

    switch (pressTabCnt) {
    case 1:
        if (pressUDCnt == 0)
            pressUDCnt = 1;
        selectedBtn = nullptr;
        if (selectedItem != nullptr)
            selectedItem->setSelected(false);
        selectedItem = toolbutton_list.at(pressUDCnt - 1);
        selectedItem->setSelected(true);
        selectedDev = selectedItem;
        qtw->scrollToItem(selectedItem);
        if (!ok_btn->isEnabled())
            ok_btn->setEnabled(true);
        return QRect();
        break;
    case 2:
        selectedItem = nullptr;
        if (!ok_btn->isVisible() || !cancel_btn->isVisible())
            ++pressTabCnt;
        if(ok_btn->isVisible()) {
            selectedBtn = ok_btn;
            return ok_btn->geometry();
        } else if (cancel_btn->isVisible()){
            selectedBtn = cancel_btn;
            return cancel_btn->geometry();
        }
        return QRect();
        break;
    case 3:
        selectedItem = nullptr;
        selectedBtn = cancel_btn;
        return cancel_btn->geometry();
        break;
    case 4:
        selectedItem = nullptr;
        selectedBtn = close_btn;
        return close_btn->geometry();
        break;
    default:
        break;
    }
}

void BluetoothFileTransferWidget::paintEvent(QPaintEvent *event) {
    QPainter pt(this);
    QColor color = QColor("#818181");
//    color.setAlpha(tran);
    pt.setPen(color);
    QRect rect;
    rect = getButton();
    pt.setRenderHint(QPainter::Antialiasing);
    pt.drawRect(rect);
}

void BluetoothFileTransferWidget::keyPressEvent(QKeyEvent *event) {
    qDebug() << Q_FUNC_INFO << event->key();
    int size = toolbutton_list.size();
    switch (event->key()) {
    case Qt::Key_Tab:
        ++pressTabCnt;
        if (pressTabCnt == 5)
            pressTabCnt = 1;
        if(send_state != _SEND_NONE && pressTabCnt == 1)
            ++pressTabCnt;
        qDebug() << Q_FUNC_INFO << "press Tab" << pressTabCnt << send_state;
        this->update();
        break;
    case Qt::Key_Down:
    case Qt::Key_Up:
        if (pressTabCnt != 1)
            return;
        (event->key() == Qt::Key_Down) ? ++pressUDCnt : --pressUDCnt;

        if (pressUDCnt > size)
            pressUDCnt = 1;
        if (pressUDCnt < 1)
            pressUDCnt = size;

        qDebug() << Q_FUNC_INFO << "press Down/Up" << pressTabCnt << pressUDCnt;

        this->update();
        break;
    case Qt::Key_Enter:
    case Qt::Key_Return:
        qDebug() << Q_FUNC_INFO << "press Enter";
        if (selectedBtn != nullptr)
            selectedBtn->clicked();
        break;
    case Qt::Key_Escape:
        qDebug() << Q_FUNC_INFO << "press Esc";
        if (pressTabCnt == 0) {
            this->close();
            if (send_state == _SENDING)
                emit close_the_pre_session();
        }
        pressTabCnt = 0;
        pressUDCnt = 0;
        selectedBtn = nullptr;
        if (selectedItem != nullptr)
            selectedItem->setSelected(false);
        selectedItem = nullptr;
        this->update();
        break;
    default:
        break;
    }
}
