#include "config.h"

Environment envPC = Environment::NOMAL;

const QString UIExe     = "/usr/bin/ukui-bluetooth";
QProcess *process = nullptr;

QGSettings* Config::gsetting = new QGSettings(GSETTING_SCHEMA_UKUIBLUETOOH);
QGSettings* Config::ukccGsetting = new QGSettings(GSETTING_SCHEMA_UKCC,GSETTING_PACH_UKCC);

Config::Config(QObject *parent)
    :QObject(parent)
{
}

Config::~Config()
{
    delete gsetting;
}

void Config::SendNotifyMessage(QString message)
{
    QDBusInterface iface("org.freedesktop.Notifications",
                             "/org/freedesktop/Notifications",
                             "org.freedesktop.Notifications",
                             QDBusConnection::sessionBus());
    QList<QVariant> args;
    args<<tr("ukui-bluetooth")
        <<((unsigned int) 0)
        <<"bluetooth"
        <<tr("Bluetooth message") //显示的是什么类型的信息
        <<message //显示的具体信息
        <<QStringList()
        <<QVariantMap()
        <<(int)-1;
    QDBusMessage msg = iface.callWithArgumentList(QDBus::AutoDetect,"Notify",args);
    qDebug() << Q_FUNC_INFO << msg.errorMessage();
}

void Config::OpenBluetoothSettings()
{
    qDebug() << Q_FUNC_INFO << __LINE__;
    //mavis 需要区分
    if (Environment::MAVIS == envPC){

        QDBusInterface *m_statusSessionDbus = new QDBusInterface("com.kylin.statusmanager.interface",
                                                                 "/",
                                                                 "com.kylin.statusmanager.interface",
                                                                 QDBusConnection::sessionBus());

        if (m_statusSessionDbus->isValid())
        {
            qInfo() << Q_FUNC_INFO << "is_tabletmode" << __LINE__;

            QDBusReply<bool> is_tabletmode = m_statusSessionDbus->call("get_current_tabletmode");
            if (is_tabletmode)
                AppManagerToOpenBluetoothSettings();
            else
                CommandToOpenBluetoothSettings();
        }
        else
            CommandToOpenBluetoothSettings();
    }
    else
        CommandToOpenBluetoothSettings();
}

void Config::AppManagerToOpenBluetoothSettings()
{
    qInfo () << Q_FUNC_INFO << "" << __LINE__;

    QDBusMessage m = QDBusMessage::createMethodCall("com.kylin.AppManager",
                                                    "/com/kylin/AppManager",
                                                    "com.kylin.AppManager",
                                                    "LaunchAppWithArguments");
    m<< QString("ukui-control-center.desktop") << QStringList{"-m","Bluetooth"};
    // qDebug() << Q_FUNC_INFO << m.arguments().at(0).value<QString>() <<__LINE__;
    // 发送Message
    QDBusConnection::sessionBus().call(m, QDBus::NoBlock);

}

void Config::CommandToOpenBluetoothSettings()
{
    qInfo () << Q_FUNC_INFO << "" << __LINE__;

    QProcess *process = new QProcess();
    QString cmd = "ukui-control-center";
    QStringList arg;
    arg.clear();
    arg << "-m";
    arg << "Bluetooth";
    qDebug() << Q_FUNC_INFO << arg;
    process->startDetached(cmd,arg);
}

void Config::LaunchUI()
{
    if(nullptr == process)
    {
        process = new QProcess();
        QString cmd = UIExe;
        qDebug() << Q_FUNC_INFO;
        QTimer::singleShot(700, process, [=]{
            process->startDetached(cmd);
        });
    }
}

QStringList Config::getDeviceConnectTimeList(QString path)
{
    QStringList pair_device_list;
    pair_device_list.clear();
    if(!QFile::exists(path))
        return pair_device_list;

    QVector<int> pair_device_time_list;
    pair_device_time_list.clear();
    GKeyFile *key_file = nullptr;
    key_file = g_key_file_new();
    g_key_file_load_from_file(key_file,QString(path).toStdString().c_str(),G_KEY_FILE_NONE,NULL);
    gchar **list;
    bool ok;
    list  = g_key_file_get_groups(key_file,NULL);
    for(int i = 0; list[i] != NULL; i++){
        pair_device_list.append(QString::fromUtf8(list[i]));
        pair_device_time_list.append(QString::fromUtf8(g_key_file_get_string(key_file,list[i],"ConnectTime",NULL)).toInt(&ok,10));
    }

    //*****************给从配置文件中得到的设备列表和设备对应的最后连接时间列表排序***********START**************
    for(int i = 0; i < pair_device_time_list.length(); i++){
        for(int j = 0; j < pair_device_time_list.length()-i-1; j++){
            if(pair_device_time_list.at(j) < pair_device_time_list.at(j+1)){
                int max = pair_device_time_list.at(j);
                pair_device_time_list.replace(j,pair_device_time_list.at(j+1));
                pair_device_time_list.replace(j+1,max);
                QString target = pair_device_list.at(j);
                pair_device_list.removeAt(j);
                pair_device_list.insert(j+1,target);
            }
        }
    }
    //************************************  END  ******************************************************

    g_key_file_free(key_file);

    return pair_device_list;
}

void Config::writeKeyFile(QString addr, QString name, qint32 type)
{
    qDebug() << Q_FUNC_INFO << addr << name << type;
    QDBusMessage m = QDBusMessage::createMethodCall("com.bluetooth.systemdbus", "/", "com.bluetooth.interface", "writeKeyFile");
    m << addr << name << type;
    QDBusMessage response = QDBusConnection::systemBus().call(m);
    qDebug() << Q_FUNC_INFO << addr << name << type << response.errorMessage();
}

void Config::removeKey(QString addr)
{
    qDebug() << Q_FUNC_INFO << addr;
    QDBusMessage m = QDBusMessage::createMethodCall("com.bluetooth.systemdbus", "/", "com.bluetooth.interface", "removeKeyFile");
    m << addr;
    QDBusMessage response = QDBusConnection::systemBus().call(m);
    qDebug() << Q_FUNC_INFO << addr << response.errorMessage();

}



