#include "dbusadapter.h"
#include <QDBusConnection>
#include <QDBusVariant>
#include <QDBusMessage>

#include "global/globalsignal.h"
#include "global/global.h"

using namespace Global; 

DbusAdapter::DbusAdapter(QObject *parent) : QObject(parent)
{
    m_currentFile = "";

    connect(g_core_signal, &GlobalCoreSignal::sigStateChange, [&](){
        if(g_playstate < 0)
            m_currentFile = "";
    });
    connect(g_core_signal, &GlobalCoreSignal::sigFileInfoChange, [&](Mpv::FileInfo fi){
        m_currentFile = fi.file_path;
    });

    QDBusConnection::sessionBus().unregisterService("org.mpris.MediaPlayer2.KylinVideo");
    QDBusConnection::sessionBus().registerService("org.mpris.MediaPlayer2.KylinVideo");
    QDBusConnection::sessionBus().registerObject("/org/mpris/MediaPlayer2", "org.mpris.MediaPlayer2.Player", this, QDBusConnection::ExportAllContents);
    QDBusConnection::sessionBus().registerObject("/org/mpris/MediaPlayer2", "org.mpris.MediaPlayer2", this, QDBusConnection::ExportAllContents);
    initMetadata();
}

void DbusAdapter::initMetadata()
{
    // 表示路径
    m_metadata.insert("mpris:trackid", 0);
    m_metadata.insert("mpris:length", 0);
    m_metadata.insert("mpris:artUrl", "");
    m_metadata.insert("xesam:album", "");
    m_metadata.insert("xesam:albumArtist", "");
    m_metadata.insert("xesam:artist", "");
    m_metadata.insert("xesam:asText", "");
    m_metadata.insert("xesam:audioBPM", 0);
    m_metadata.insert("xesam:autoRating", 0.0);
    QStringList commont;
    m_metadata.insert("xesam:comment", commont);
    QStringList composer;
    m_metadata.insert("xesam:composer", composer);
    m_metadata.insert("xesam:contentCreated", "");
    m_metadata.insert("xesam:discNumber", 0);
    m_metadata.insert("xesam:firstUsed", "");
    QStringList genre;
    m_metadata.insert("xesam:genre", genre);
    m_metadata.insert("xesam:lastUsed", "");
    QStringList lyricist;
    m_metadata.insert("xesam:lyricist", lyricist);
    m_metadata.insert("xesam:title", "");
    m_metadata.insert("xesam:trackNumber", 0);
    m_metadata.insert("xesam:url", "");
    m_metadata.insert("xesam:useCount", 0);
    m_metadata.insert("xesam:userRating", 0.0);
}

void DbusAdapter::Stop() const
{
    g_user_signal->stop();
    // 手动停止之后需要显示默认界面
    g_user_signal->showStopFrame();
}

void DbusAdapter::Next() const
{
    g_user_signal->playNext(true);
}

double DbusAdapter::getRate()
{
    qDebug() << "getRate";
//    g_user_signal->getSpeed();
    return 1;
}

void DbusAdapter::setRate(double d)
{
    qDebug() << "setRate:" << d;
    if (d >= m_minimumRate && d <= m_maximumRate) {
        g_user_signal->setSpeed(d);
    } else {
        qWarning() << "dbus set rate error, rate is :" << d;
    }
//    QStringList changeList { QString::number(d) };
//    notify("Rate", changeList);
}

QString DbusAdapter::getLoopStatus()
{
//    return Widget::mutual->getPlayMode();
    return 0;
}

void DbusAdapter::Seek(const qint64 Offset)
{
    if (Offset > 0)
        g_user_signal->sigForword(true);
    else
        g_user_signal->sigBackword(true);
}

void DbusAdapter::setVolume(double d)
{
//    if (d < 0) {
//        d = 0;
//    } else if (d > 1) {
//        qWarning() << "setVolume error, bigger than 1, volume is :" << d;
//        return;
//    }

//    Widget::mutual->setVolume(d*100);

//    QStringList changeList { QString::number(d) };
//    notify("Volume", changeList);
    return;
}


void DbusAdapter::setLoopStatus(QString s)
{
//    Widget::mutual->setPlayMode(s);
    return;
}

double DbusAdapter::getVolume()
{
//    return double(Widget::mutual->getVolume()) / 100;
//    return 0;
    return 1;
}

void DbusAdapter::KvPlayPause() const
{
    if(g_playstate == Mpv::Paused)
        g_user_signal->play();
    else if(g_playstate == Mpv::Playing)
        g_user_signal->pause();
    else if (g_playstate == Mpv::Stopped)
        g_user_signal->stop();
}

void DbusAdapter::Play()
{
    g_user_signal->play();

    QVariantMap changedProperties;
    changedProperties.insert("PlaybackStatus",QVariant::fromValue(QDBusVariant(m_playbackStatus)));
    notify("org.mpris.MediaPlayer2.Player",changedProperties,QStringList());
}

void DbusAdapter::Pause()
{
    g_user_signal->pause();

    QVariantMap changedProperties;
    changedProperties.insert("PlaybackStatus",QVariant::fromValue(QDBusVariant(m_playbackStatus)));
    notify("org.mpris.MediaPlayer2.Player",changedProperties,QStringList());
}

void DbusAdapter::PlayPause()
{
    if(g_playstate == Mpv::Paused)
        g_user_signal->play();
    else if(g_playstate == Mpv::Playing)
        g_user_signal->pause();
    else if (g_playstate == Mpv::Stopped)
        g_user_signal->stop();

    QVariantMap changedProperties;
    changedProperties.insert("PlaybackStatus",QVariant::fromValue(QDBusVariant(m_playbackStatus)));
    notify("org.mpris.MediaPlayer2.Player",changedProperties,QStringList());
}

void DbusAdapter::notify(const QString &interfaceName, const QVariantMap &changedProperties, const QStringList &invalidatedProperties)
{
    QDBusConnection connection = QDBusConnection::sessionBus();
    QString objectPath = "/org/mpris/MediaPlayer2";
    QDBusMessage signalMessage= QDBusMessage::createSignal(objectPath,"org.freedesktop.DBus.Properties","PropertiesChanged");
    signalMessage << interfaceName << changedProperties << invalidatedProperties;
    connection.send(signalMessage);
}

void DbusAdapter::Previous() const
{
    g_user_signal->playPrev(true);
}

void DbusAdapter::AddFile(QString file) const
{
    g_user_signal->addFiles(QStringList() << file);
}

void DbusAdapter::VolumeUp() const
{
    g_user_signal->setVolumeUp(10);
}

void DbusAdapter::VolumeDown() const
{
    g_user_signal->setVolumeDown(10);
}

void DbusAdapter::FullScreen() const
{
    g_user_signal->fullScreen();
}

void DbusAdapter::LoopMode() const
{
    g_user_signal->changePlayOrder();
}

void DbusAdapter::Exit() const
{
    g_user_signal->exitApp();
}

/**
 * 返回播放状态
 * @return:
 *  -1  :停止
 *  0   :暂停
 *  1   :播放
 */
int DbusAdapter::PlayState()
{
    if(g_playstate == Mpv::Playing)
        return 1;
    else if(g_playstate == Mpv::Paused)
        return 0;
    else
        return -1;
}

/**
 * @brief DbusAdapter::getState 当前音视频播放状态
 *
 * @note 当系统重启后任务栏也不生效时，需要 `killall ukui-panel` 重启任务栏验证
 *
 * @return
 *      "Playing" ： 播放
 *      "Paused" ： 暂停
 *      "Stopped" ： 停止
 */
QString DbusAdapter::getPlaybackState()
{
    if (g_playstate == Mpv::Playing) {
        return PLAY_STATUS;
    } else if (g_playstate == Mpv::Paused) {
        return PAUSED_STATUS;
    } else {
        return STOP_STATUS;
    }
}

QString DbusAdapter::CurrentFile()
{
    return m_currentFile;
}
